<?php
/**
 * 用户分群
 * Created by PhpStorm.
 * User: Liujianlin
 * Date: 2017/6/24
 * Time: 15:00
 */

namespace app\controllers\marketing;

use app\models\crontab\CrmPush\UserLabelQueue;
use app\models\crontab\CrmPush\UserLabelQueueDetail;
use app\models\marketing\UserGroup;
use app\models\marketing\MailGroup;
use app\models\marketing\User;
use app\models\marketing\QuickUserGroup;
use app\models\marketing\Category;
use app\models\marketing\UserTag;
use yii;
use app\components\Site;
use app\components\TemplateMarket;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;
use app\components\redis\RedisMarketingEmail;
use app\components\UserManageMarket;
use app\models\marketing\MailSendlist;
use app\components\SplitSendlist;

class UserGroupController extends \app\base\Controller
{
    public function init()
    {
        parent::init();
        $this->enableCsrfValidation = false;        // 禁用post的csrf验证
    }

    /**
     * 分群列表
     * @return string
     */
    public function actionIndex()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $reviserRealName = yii::$app->request->$method("reviser_real_name");
        $regSourceParam = yii::$app->request->$method("reg_source");
        $type = yii::$app->request->$method("type");

        $userGroupModel = new UserGroup();
        $condition['is_del'] = 0;
        $condition['user_group_type'] = 1;
        if (empty($siteId)) {
            if (empty($accessSiteInfo)) {
                $this->sysMsg('警告', '你的账号没有权限!',
                    ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
            }
            $curSite = current($accessSiteInfo);
            $siteId = $curSite['site_id'];
        }
        $condition['site_id'] = $siteId;

        $this->checkSitePrivilege($siteId);    // 校验用户是否具有站点的权限

        if (empty($reviserRealName)) {
            $session = Yii::$app->session;
            $reviserRealName = $session['admin_info']['real_name'];
        }
        if ($reviserRealName != "全部") {
            $condition['reviser_real_name'] = $reviserRealName;
        }
        if (!empty($regSourceParam) && $regSourceParam != "ALL") {  //非全站时添加，注册来源筛选
            $condition['reg_source'] = $regSourceParam;
        }
        $groupList = $userGroupModel->getByCondition($condition, "order by user_group_id desc");


        foreach ($groupList as $key => $group) {
            $formData = json_decode($group['form_data'], true);
            $groupList[$key]['item'] = $this->getPreviewItem($formData);
        }
        $reviser = $userGroupModel->getReviser();
        array_unshift($reviser, ["reviser_real_name" => "全部"]);
        $sysGroup = $userGroupModel->getSysGroup($siteId);
        $condition['user_group_type'] = 8; // 第三方标签分群
        $tagGroupList = $userGroupModel->getByCondition($condition, "order by update_time desc");
        // author xianxuefeng
        $sql = "select id as reg_id,reg_source,website_name from reg_source where site_id = $siteId";
        $resSourceInfo = yii::$app->db->createCommand($sql)->queryAll();

        if (empty($resSourceInfo)) {   //如果为空，默认返回全球站
            $regSourceArr = [];
        } else {
            $temp[] = ['reg_source' => 'ALL', 'website_name' => '全站'];
            $resSourceInfo = array_merge($temp, $resSourceInfo);
            $regSourceArr = ArrayHelper::map($resSourceInfo, 'reg_source', 'website_name');
        }

        //选中后，刷新页面出现选中信息
        $defaultIndex = 'ALL';
        if (!empty($regSourceParam)) {
            $defaultIndex = $regSourceParam;
        }
        $regSource['defaultIndex'] = $defaultIndex;
        $regSource['regSource'] = $regSourceArr;

        // 快捷发送分群
        // 按添加时间由近到远获取当前站点对应的100条记录
        $quickUserGroupModel = new QuickUserGroup();
        $datas = $quickUserGroupModel->getAllDatas($siteId, $defaultIndex);
        $quickUserGroupIds = [];
        foreach ($datas as $key => $data) {
            $userDefineGroupIds = json_decode($data['user_define_group_ids'], true);
            $userSysGroupIds = json_decode($data['user_sys_group_ids'], true);
            $userExtendGroupIds = json_decode($data['user_extend_group_ids'], true);
            $datas[$key]['user_define_group_ids'] = [];
            if ($userDefineGroupIds && is_array($userDefineGroupIds)) {
                $quickUserGroupIds = array_merge($quickUserGroupIds, $userDefineGroupIds);
                $datas[$key]['user_define_group_ids'] = $userDefineGroupIds;
            }
            $datas[$key]['user_extend_group_ids'] = [];
            if ($userExtendGroupIds && is_array($userExtendGroupIds)) {
                $quickUserGroupIds = array_merge($quickUserGroupIds, $userExtendGroupIds);
                $datas[$key]['user_extend_group_ids'] = $userExtendGroupIds;
            }
            $datas[$key]['user_sys_group_ids'] = [];
            if ($userSysGroupIds && is_array($userSysGroupIds)) {
                foreach ($userSysGroupIds as $userSysGroupId) {
                    if ($userSysGroupId && is_array($userSysGroupId)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userSysGroupId);
                    }
                }
                $datas[$key]['user_sys_group_ids'] = $userSysGroupIds;
            }

        }
        $userGroups = [];
        $quickUserGroupIds = array_unique($quickUserGroupIds);
        if ($quickUserGroupIds) {
            $userGroupModel = new UserGroup();
            $userGroupInfo = $userGroupModel->getMultiUserGroupByIds($siteId, $quickUserGroupIds);
            foreach ($userGroupInfo as $userGroup) {
                $userGroups[$userGroup['user_group_id']] = $userGroup['user_group_name'];
            }
        }
        foreach ($datas as $key => $data) {
            $datas[$key]['user_define_group_ids'] = [];
            if ($data['user_define_group_ids']) {
                foreach ($data['user_define_group_ids'] as $define) {
                    if (isset($userGroups[$define])) {
                        $datas[$key]['user_define_group_ids'][] = ['user_group_id' => $define, 'user_group_name' => $userGroups[$define]];
                    }
                }
            }
            $datas[$key]['user_extend_group_ids'] = [];
            if ($data['user_extend_group_ids']) {
                foreach ($data['user_extend_group_ids'] as $extend) {
                    if (isset($userGroups[$extend])) {
                        $datas[$key]['user_extend_group_ids'][] = ['user_group_id' => $extend, 'user_group_name' => $userGroups[$extend]];
                    }
                }
            }
            $datas[$key]['user_sys_group_ids'] = [];
            if ($data['user_sys_group_ids']) {
                foreach ($data['user_sys_group_ids'] as $syskey => $sys) {
                    foreach ($sys as $sysval) {
                        if (isset($userGroups[$sysval])) {
                            $datas[$key]['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval]];
                        }
                    }
                }
            }
        }
        $returnDatas['datas'] = $datas;
        //                $returnDatas['userGroupInfo'] = $userGroupInfo;
        $returnDatas['count'] = count($datas);
        //var_dump($returnDatas);exit;

        $viewer = '//marketing/user-group/list';
        // EBAY 站点手动上传用户分群
        if ($siteId == 31) {
            $viewer = '//marketing/user-group/ebay-list';
            return $this->render($viewer,
                ["siteInfo" => $accessSiteInfo, "tagGroupList" => $tagGroupList,
                    "reviser" => $reviser, "quick_user_group" => $returnDatas,
                    "requestData" => ["site_id" => $siteId, "reviser_real_name" => $reviserRealName],
                    'regSource' => $regSource
                ]);
        }

        return $this->render($viewer,
            ["siteInfo" => $accessSiteInfo, "groupList" => $groupList,
                'sysGroup' => $sysGroup, "reviser" => $reviser, "quick_user_group" => $returnDatas,
                "requestData" => ["site_id" => $siteId, "reviser_real_name" => $reviserRealName],
                'regSource' => $regSource, 'type' => $type
            ]);
    }

    /**
     * 分群列表
     * @return string
     */
    public function actionLangria()
    {
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $reviserRealName = yii::$app->request->$method("reviser_real_name");
        $regSourceParam = yii::$app->request->$method("reg_source");
        $type = yii::$app->request->$method("type");

        $userGroupModel = new UserGroup();
        $condition['is_del'] = 0;
        $condition['user_group_type'] = 1;
        if (empty($siteId)) {
            if (empty($accessSiteInfo)) {
                $this->sysMsg('警告', '你的账号没有权限!',
                    ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
            }
            $curSite = current($accessSiteInfo);
            $siteId = $curSite['site_id'];
        }
        $condition['site_id'] = $siteId;

        $this->checkSitePrivilege($siteId);    // 校验用户是否具有站点的权限

        if (empty($reviserRealName)) {
            $session = Yii::$app->session;
            $reviserRealName = $session['admin_info']['real_name'];
        }
        if ($reviserRealName != "全部") {
            $condition['reviser_real_name'] = $reviserRealName;
        }
        if (!empty($regSourceParam) && $regSourceParam != "ALL") {  //非全站时添加，注册来源筛选
            $condition['reg_source'] = $regSourceParam;
        }
        $groupList = $userGroupModel->getByCondition($condition, "order by user_group_id desc");


        foreach ($groupList as $key => $group) {
            $formData = json_decode($group['form_data'], true);
            $groupList[$key]['item'] = $this->getPreviewItem($formData);
        }
        $reviser = $userGroupModel->getReviser();
        array_unshift($reviser, ["reviser_real_name" => "全部"]);
        $sysGroup = $userGroupModel->getSysGroup($siteId);
        $condition['user_group_type'] = 8; // 第三方标签分群
        $tagGroupList = $userGroupModel->getByCondition($condition, "order by update_time desc");
        // author xianxuefeng
        $sql = "select id as reg_id,reg_source,website_name from reg_source where site_id = $siteId";
        $resSourceInfo = yii::$app->db->createCommand($sql)->queryAll();

        if (empty($resSourceInfo)) {   //如果为空，默认返回全球站
            $regSourceArr = [];
        } else {
            $temp[] = ['reg_source' => 'ALL', 'website_name' => '全站'];
            $resSourceInfo = array_merge($temp, $resSourceInfo);
            $regSourceArr = ArrayHelper::map($resSourceInfo, 'reg_source', 'website_name');
        }

        //选中后，刷新页面出现选中信息
        $defaultIndex = 'ALL';
        if (!empty($regSourceParam)) {
            $defaultIndex = $regSourceParam;
        }
        $regSource['defaultIndex'] = $defaultIndex;
        $regSource['regSource'] = $regSourceArr;

        // 快捷发送分群
        // 按添加时间由近到远获取当前站点对应的100条记录
        $quickUserGroupModel = new QuickUserGroup();
        $datas = $quickUserGroupModel->getAllDatas($siteId, $defaultIndex);
        $quickUserGroupIds = [];
        foreach ($datas as $key => $data) {
            $userDefineGroupIds = json_decode($data['user_define_group_ids'], true);
            $userSysGroupIds = json_decode($data['user_sys_group_ids'], true);
            $userExtendGroupIds = json_decode($data['user_extend_group_ids'], true);
            $datas[$key]['user_define_group_ids'] = [];
            if ($userDefineGroupIds && is_array($userDefineGroupIds)) {
                $quickUserGroupIds = array_merge($quickUserGroupIds, $userDefineGroupIds);
                $datas[$key]['user_define_group_ids'] = $userDefineGroupIds;
            }
            $datas[$key]['user_extend_group_ids'] = [];
            if ($userExtendGroupIds && is_array($userExtendGroupIds)) {
                $quickUserGroupIds = array_merge($quickUserGroupIds, $userExtendGroupIds);
                $datas[$key]['user_extend_group_ids'] = $userExtendGroupIds;
            }
            $datas[$key]['user_sys_group_ids'] = [];
            if ($userSysGroupIds && is_array($userSysGroupIds)) {
                foreach ($userSysGroupIds as $userSysGroupId) {
                    if ($userSysGroupId && is_array($userSysGroupId)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userSysGroupId);
                    }
                }
                $datas[$key]['user_sys_group_ids'] = $userSysGroupIds;
            }

        }
        $userGroups = [];
        $quickUserGroupIds = array_unique($quickUserGroupIds);
        if ($quickUserGroupIds) {
            $userGroupModel = new UserGroup();
            $userGroupInfo = $userGroupModel->getMultiUserGroupByIds($siteId, $quickUserGroupIds);
            foreach ($userGroupInfo as $userGroup) {
                $userGroups[$userGroup['user_group_id']] = $userGroup['user_group_name'];
            }
        }
        foreach ($datas as $key => $data) {
            $datas[$key]['user_define_group_ids'] = [];
            if ($data['user_define_group_ids']) {
                foreach ($data['user_define_group_ids'] as $define) {
                    if (isset($userGroups[$define])) {
                        $datas[$key]['user_define_group_ids'][] = ['user_group_id' => $define, 'user_group_name' => $userGroups[$define]];
                    }
                }
            }
            $datas[$key]['user_extend_group_ids'] = [];
            if ($data['user_extend_group_ids']) {
                foreach ($data['user_extend_group_ids'] as $extend) {
                    if (isset($userGroups[$extend])) {
                        $datas[$key]['user_extend_group_ids'][] = ['user_group_id' => $extend, 'user_group_name' => $userGroups[$extend]];
                    }
                }
            }
            $datas[$key]['user_sys_group_ids'] = [];
            if ($data['user_sys_group_ids']) {
                foreach ($data['user_sys_group_ids'] as $syskey => $sys) {
                    foreach ($sys as $sysval) {
                        if (isset($userGroups[$sysval])) {
                            $datas[$key]['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval]];
                        }
                    }
                }
            }
        }
        $returnDatas['datas'] = $datas;
        //                $returnDatas['userGroupInfo'] = $userGroupInfo;
        $returnDatas['count'] = count($datas);
        //var_dump($returnDatas);exit;

        $viewer = '//marketing/user-group/list';
        // EBAY 站点手动上传用户分群
        if ($siteId == 25) {
            $viewer = '//marketing/user-group/langria';
            return $this->render($viewer,
                ["siteInfo" => $accessSiteInfo, "tagGroupList" => $tagGroupList,
                    "reviser" => $reviser, "quick_user_group" => $returnDatas,
                    "requestData" => ["site_id" => $siteId, "reviser_real_name" => $reviserRealName],
                    'regSource' => $regSource
                ]);
        }

        return $this->render($viewer,
            ["siteInfo" => $accessSiteInfo, "groupList" => $groupList,
                'sysGroup' => $sysGroup, "reviser" => $reviser, "quick_user_group" => $returnDatas,
                "requestData" => ["site_id" => $siteId, "reviser_real_name" => $reviserRealName],
                'regSource' => $regSource, 'type' => $type
            ]);
    }


    /*
     * 添加快捷发送分群
     * liugang 2018-5-28
     */
    public function actionAddQuickUserGroup()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $formDatas = yii::$app->request->$method();

        $quickUserGroupModel = new QuickUserGroup();
//        var_dump($formDatas);

        if (!Yii::$app->authority->judgeMarketEmailHaveSite($siteId)) {
            $return = ['status' => 10007, 'errorInfo' => '你的账号没有权限!', 'datas' => []];
            return json_encode($return);
        }
        if (!$formDatas['real_quick_user_group_name']) {
            $return = ['status' => 10007, 'errorInfo' => '快捷发送分群名称不能为空!', 'datas' => []];
            return json_encode($return);
        }

        $condition = [
            'site_id' => intval($siteId),
            'quick_user_group_name' => trim($formDatas['real_quick_user_group_name']),
        ];
        $sysGroupArr = [];
        for ($i = 1; $i <= 6; $i++) {
            if (isset($formDatas['sys_group' . $i]) && is_array($formDatas['sys_group' . $i])) {
                $sysGroupArr[$i] = $formDatas['sys_group' . $i];
            }
        }
        $regSource = '';
        if (isset($formDatas['reg_source']) && $formDatas['reg_source'] != 'ALL') {
            $condition['reg_source'] = $regSource = $formDatas['reg_source'];
        }
        $condition['user_sys_group_ids'] = $sysGroupArr ? json_encode($sysGroupArr) : '';
        $condition['user_define_group_ids'] = isset($formDatas['user_define_group']) && is_array($formDatas['user_define_group']) ? json_encode($formDatas['user_define_group']) : '';
        $condition['user_extend_group_ids'] = isset($formDatas['exclude_group']) && is_array($formDatas['exclude_group']) ? json_encode($formDatas['exclude_group']) : '';

        if ($quickId = $quickUserGroupModel->getOne($siteId, $formDatas['real_quick_user_group_name'])) {
            $condition['update_time'] = yii::$app->bjTime->time();
            if ($quickUserGroupModel->updateQuickUserGroup($quickId, $condition)) {
                // 按添加时间由近到远获取当前站点对应的100条记录
                $datas = $quickUserGroupModel->getAllDatas($siteId, $regSource);
                $quickUserGroupIds = [];
                foreach ($datas as $key => $data) {
                    $userDefineGroupIds = json_decode($data['user_define_group_ids'], true);
                    $userSysGroupIds = json_decode($data['user_sys_group_ids'], true);
                    $userExtendGroupIds = json_decode($data['user_extend_group_ids'], true);
                    $datas[$key]['user_define_group_ids'] = [];
                    if ($userDefineGroupIds && is_array($userDefineGroupIds)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userDefineGroupIds);
                        $datas[$key]['user_define_group_ids'] = $userDefineGroupIds;
                    }
                    $datas[$key]['user_extend_group_ids'] = [];
                    if ($userExtendGroupIds && is_array($userExtendGroupIds)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userExtendGroupIds);
                        $datas[$key]['user_extend_group_ids'] = $userExtendGroupIds;
                    }
                    $datas[$key]['user_sys_group_ids'] = [];
                    if ($userSysGroupIds && is_array($userSysGroupIds)) {
                        foreach ($userSysGroupIds as $userSysGroupId) {
                            if ($userSysGroupId && is_array($userSysGroupId)) {
                                $quickUserGroupIds = array_merge($quickUserGroupIds, $userSysGroupId);
                            }
                        }
                        $datas[$key]['user_sys_group_ids'] = $userSysGroupIds;
                    }

                }
                $userGroups = [];
                $quickUserGroupIds = array_unique($quickUserGroupIds);
                if ($quickUserGroupIds) {
                    $userGroupModel = new UserGroup();
                    $userGroupInfo = $userGroupModel->getMultiUserGroupByIds($siteId, $quickUserGroupIds);
                    foreach ($userGroupInfo as $userGroup) {
                        $userGroups[$userGroup['user_group_id']] = $userGroup['user_group_name'];
                    }
                }

                foreach ($datas as $key => $data) {
                    $datas[$key]['user_define_group_ids'] = [];
                    if ($data['user_define_group_ids']) {
                        foreach ($data['user_define_group_ids'] as $define) {
                            if (isset($userGroups[$define])) {
                                $datas[$key]['user_define_group_ids'][] = ['user_group_id' => $define, 'user_group_name' => $userGroups[$define]];
                            }
                        }
                    }
                    $datas[$key]['user_extend_group_ids'] = [];
                    if ($data['user_extend_group_ids']) {
                        foreach ($data['user_extend_group_ids'] as $extend) {
                            if (isset($userGroups[$extend])) {
                                $datas[$key]['user_extend_group_ids'][] = ['user_group_id' => $extend, 'user_group_name' => $userGroups[$extend]];
                            }
                        }
                    }
                    $datas[$key]['user_sys_group_ids'] = [];
                    if ($data['user_sys_group_ids']) {
                        foreach ($data['user_sys_group_ids'] as $syskey => $sys) {
                            foreach ($sys as $sysval) {
                                if (isset($userGroups[$sysval])) {
                                    $datas[$key]['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval]];
                                }
                            }
                        }
                    }
                }
                $returnDatas['datas'] = $datas;
//                $returnDatas['userGroupInfo'] = $userGroupInfo;
                $returnDatas['count'] = count($datas);
//                var_dump(json_encode($returnDatas));exit;

                $return = ['status' => 0, 'errorInfo' => '', 'datas' => $returnDatas];
                return json_encode($return);
            } else {
                $return = ['status' => 10007, 'errorInfo' => '数据保存失败!', 'datas' => []];
                return json_encode($return);
            }
        } else {
            $condition['add_time'] = yii::$app->bjTime->time();
            if ($quickUserGroupModel->addQuickUserGroup($condition)) {
                // 按添加时间由近到远获取当前站点对应的100条记录
                $datas = $quickUserGroupModel->getAllDatas($siteId, $regSource);
                $quickUserGroupIds = [];
                foreach ($datas as $key => $data) {
                    $userDefineGroupIds = json_decode($data['user_define_group_ids'], true);
                    $userSysGroupIds = json_decode($data['user_sys_group_ids'], true);
                    $userExtendGroupIds = json_decode($data['user_extend_group_ids'], true);
                    $datas[$key]['user_define_group_ids'] = [];
                    if ($userDefineGroupIds && is_array($userDefineGroupIds)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userDefineGroupIds);
                        $datas[$key]['user_define_group_ids'] = $userDefineGroupIds;
                    }
                    $datas[$key]['user_extend_group_ids'] = [];
                    if ($userExtendGroupIds && is_array($userExtendGroupIds)) {
                        $quickUserGroupIds = array_merge($quickUserGroupIds, $userExtendGroupIds);
                        $datas[$key]['user_extend_group_ids'] = $userExtendGroupIds;
                    }
                    $datas[$key]['user_sys_group_ids'] = [];
                    if ($userSysGroupIds && is_array($userSysGroupIds)) {
                        foreach ($userSysGroupIds as $userSysGroupId) {
                            if ($userSysGroupId && is_array($userSysGroupId)) {
                                $quickUserGroupIds = array_merge($quickUserGroupIds, $userSysGroupId);
                            }
                        }
                        $datas[$key]['user_sys_group_ids'] = $userSysGroupIds;
                    }

                }
                $userGroups = [];
                $quickUserGroupIds = array_unique($quickUserGroupIds);
                if ($quickUserGroupIds) {
                    $userGroupModel = new UserGroup();
                    $userGroupInfo = $userGroupModel->getMultiUserGroupByIds($siteId, $quickUserGroupIds);
                    foreach ($userGroupInfo as $userGroup) {
                        $userGroups[$userGroup['user_group_id']] = $userGroup['user_group_name'];
                    }
                }

                foreach ($datas as $key => $data) {
                    $datas[$key]['user_define_group_ids'] = [];
                    if ($data['user_define_group_ids']) {
                        foreach ($data['user_define_group_ids'] as $define) {
                            if (isset($userGroups[$define])) {
                                $datas[$key]['user_define_group_ids'][] = ['user_group_id' => $define, 'user_group_name' => $userGroups[$define]];
                            }
                        }
                    }
                    $datas[$key]['user_extend_group_ids'] = [];
                    if ($data['user_extend_group_ids']) {
                        foreach ($data['user_extend_group_ids'] as $extend) {
                            if (isset($userGroups[$extend])) {
                                $datas[$key]['user_extend_group_ids'][] = ['user_group_id' => $extend, 'user_group_name' => $userGroups[$extend]];
                            }
                        }
                    }
                    $datas[$key]['user_sys_group_ids'] = [];
                    if ($data['user_sys_group_ids']) {
                        foreach ($data['user_sys_group_ids'] as $syskey => $sys) {
                            foreach ($sys as $sysval) {
                                if (isset($userGroups[$sysval])) {
                                    $datas[$key]['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval]];
                                }
                            }
                        }
                    }
                }

                $returnDatas['datas'] = $datas;
//                $returnDatas['userGroupInfo'] = $userGroupInfo;
                $returnDatas['count'] = count($datas);


                $return = ['status' => 0, 'errorInfo' => '', 'datas' => $returnDatas];
                return json_encode($return);
            } else {
                $return = ['status' => 10007, 'errorInfo' => '数据保存失败!', 'datas' => []];
                return json_encode($return);
            }
        }

    }

    /*
     * 获取指定id的快捷发送分群
     */
    public function actionGetQuickUserGroupById()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $id = yii::$app->request->$method('id');
        $regSource = yii::$app->request->$method('reg_source');

        if (!Yii::$app->authority->judgeMarketEmailHaveSite($siteId)) {
            $return = ['status' => 10007, 'errorInfo' => '你的账号没有权限!', 'datas' => []];
            return json_encode($return);
        }
        $quickUserGroupModel = new QuickUserGroup();
        $data = $quickUserGroupModel->getOneById($siteId, $id);

        $quickUserGroupIds = [];
        $userDefineGroupIds = json_decode($data['user_define_group_ids'], true);
        $userSysGroupIds = json_decode($data['user_sys_group_ids'], true);
        $userExtendGroupIds = json_decode($data['user_extend_group_ids'], true);

        if ($userDefineGroupIds && is_array($userDefineGroupIds)) {
            $quickUserGroupIds = array_merge($quickUserGroupIds, $userDefineGroupIds);

        }

        if ($userExtendGroupIds && is_array($userExtendGroupIds)) {
            $quickUserGroupIds = array_merge($quickUserGroupIds, $userExtendGroupIds);

        }
        $userFlag = [];
        if ($userSysGroupIds && is_array($userSysGroupIds)) {
            foreach ($userSysGroupIds as $key => $userSysGroupId) {
                if ($userSysGroupId && is_array($userSysGroupId)) {
                    $quickUserGroupIds = array_merge($quickUserGroupIds, $userSysGroupId);
                }

                if ($key == 6) {
                    $userFlag = $userSysGroupId;
                }
            }

        }


        $userGroups = $userGroupType = $userFlagName = $realUserFlags = [];
        $quickUserGroupIds = array_unique($quickUserGroupIds);
        if ($quickUserGroupIds) {
            $userGroupModel = new UserGroup();
            $userGroupInfo = $userGroupModel->getvalidMultiUserGroupByIds($siteId, $quickUserGroupIds);
            foreach ($userGroupInfo as $userGroup) {
                $userGroups[$userGroup['user_group_id']] = $userGroup['user_group_name'];

                $userGroupType[$userGroup['user_group_id']] = intval($userGroup['user_group_type']);
            }
        }
//        var_dump($userGroupType);exit;
        if ($userFlag) {
            foreach ($userFlag as $userFlagOne) {
                if (isset($userGroups[$userFlagOne])) {
                    $userFlagName[$userFlagOne] = "'" . $userGroups[$userFlagOne] . "'";
                }
            }
            if ($userFlagName) {
                $userModel = new User();
                $userFlagInfo = $userModel->getExsitUsersFlag($siteId, $userFlagName);
                foreach ($userFlagInfo as $userFlagVal) {
                    if ($userFlagVal['user_count'] > 0) {
                        $userFlagId = array_search("'" . $userFlagVal['user_flag'] . "'", $userFlagName);
                        $realUserFlags[$userFlagId] = $userFlagVal['user_flag'];
                    }
                }
            }
        }

        $data['user_define_group_ids'] = [];
        if ($userDefineGroupIds) {
            foreach ($userDefineGroupIds as $define) {
                if (isset($userGroups[$define])) {
                    $data['user_define_group_ids'][] = ['user_group_id' => $define, 'user_group_name' => $userGroups[$define], 'user_group_type' => ($userGroupType[$define] - 1)];
                }

            }
        }
        $data['user_extend_group_ids'] = [];
        if ($userExtendGroupIds) {
            foreach ($userExtendGroupIds as $extend) {
                if (isset($userGroups[$extend])) {
                    $data['user_extend_group_ids'][] = ['user_group_id' => $extend, 'user_group_name' => $userGroups[$extend], 'user_group_type' => ($userGroupType[$extend] - 1)];
                }
            }
        }
        $data['user_sys_group_ids'] = [];
        if ($userSysGroupIds) {
            foreach ($userSysGroupIds as $syskey => $sys) {
                foreach ($sys as $sysval) {
                    if (isset($userGroups[$sysval])) {
                        if ($syskey == 6 && isset($realUserFlags[$sysval])) {
                            $data['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval], 'user_group_type' => ($userGroupType[$sysval] - 1)];
                        } else if ($syskey != 6) {
                            $data['user_sys_group_ids'][$syskey][] = ['user_group_id' => $sysval, 'user_group_name' => $userGroups[$sysval], 'user_group_type' => ($userGroupType[$sysval] - 1)];
                        }
                    }
                }
            }
        }
        $return = ['status' => 0, 'errorInfo' => '', 'datas' => $data];
        return json_encode($return);
    }

    /*
     * 删除快捷发送分群
     */
    public function actionDelQuickUserGroup()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        $id = yii::$app->request->$method("id");
        if (!Yii::$app->authority->judgeMarketEmailHaveSite($siteId)) {
            $return = ['status' => 10007, 'errorInfo' => '你的账号没有权限!', 'datas' => []];
            return json_encode($return);
        }
        $quickUserGroupModel = new QuickUserGroup();
        if ($quickUserGroupModel->delQuickUserGroup($siteId, $id)) {
            $count = $quickUserGroupModel->getAllDatasNum($siteId);
            $return = ['status' => 0, 'errorInfo' => '', 'datas' => ['count' => $count]];
            return json_encode($return);
        } else {
            $return = ['status' => 10007, 'errorInfo' => '快捷发送分群删除失败!', 'datas' => []];
            return json_encode($return);
        }
    }

    /**
     *  添加ebay标签名相关
     */
    public function actionEbayTagSubmitAjax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $userGroupModel = new UserGroup();
        $session = Yii::$app->session;
        $data = [];
        $data['reviser_real_name'] = $session['admin_info']['real_name'];
        $data['user_group_type'] = 8; // ebay标签模板
        $data['is_sys'] = 0;
        $returnData = [];
        // 处理数据是否合法
        $returnData['status'] = 0;
        if (!empty($_GET['site_id'])) {
            $formData['site_id'] = intval($_GET['site_id']);
        } else {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "为传送site_id值";
            echo json_encode($returnData);
            exit;
        }
        // 判断分群名称是否有填写
        $formData['user_group_name'] = trim($formData['user_group_name']);
//        if (empty($formData['site_id']) || empty($formData['user_group_name']) || empty(trim($formData['user_group_name']))) {
        if (empty($formData['site_id']) || empty($formData['user_group_name'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "分群名称未填写";
            echo json_encode($returnData);
            exit;
        }
        $data['user_group_name'] = $formData['user_group_name'];
        $data['site_id'] = $formData['site_id'];
        // 判断当前用户权限
        $flag = Yii::$app->authority->judgeMarketEmailHaveSite($formData['site_id']);
        if (!$flag) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "你的账号该没有权限!";
            echo json_encode($returnData);
            exit;
        }

        // 判断当前是编辑还是添加操作
        if (!empty($formData['user_group_id'])) {
            // 编辑
            // 判断分群名称是否重复
            $data['user_group_id'] = $formData['user_group_id'];
            $isDup = $this->isDuplicate($formData['site_id'], $formData['user_group_name'], $formData['user_group_id']);
        } else {
            // 添加
            $isDup = $this->isDuplicate($formData['site_id'], $formData['user_group_name']);
        }

        if ($isDup) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "该分群名称已在当前第三方网站平台下被使用，请重新输入!";
            echo json_encode($returnData);
            exit;
        } else {
            if (!empty($formData['user_group_id'])) {
                $userGroupModel->updateUserGroupTag($data);
            } else {
                $returnData['user_group_id'] = $userGroupModel->addUserGroupTag($data, 1);
            }

            $returnData['status'] = 0;
            $returnData['errorInfo'] = "success!";
            echo json_encode($returnData);
            exit;
        }
    }

    /**
     * yumao
     * 2018-5-21
     * 删除分群中用户
     */
    public function actionEbayDelAjax()
    {
        $mothod = strtolower(Yii::$app->request->getMethod());
        $formData = yii::$app->request->$mothod();

        $returnData = []; // 返回信息

        // 查询当前分组是否是属于当前用户
        $session = Yii::$app->session;
        $reviserRealName = $session['admin_info']['real_name'];
        if (empty($formData['user_group_id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "没有传递user_group_id";
            echo json_encode($returnData);
            exit;
        }
        if (empty($formData['id'])) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "没有传递id";
            echo json_encode($returnData);
            exit;
        }
        $userGroupId = intval($formData['user_group_id']);
        $userTagRedisKey = "usertag_ebay_{$userGroupId}";
        $id = intval($formData['id']);
        // 查看当前分群是否属于当前用户
        $userGroup = new UserGroup();
        $userGroupInfo = $userGroup->getUserGroupById($userGroupId, 1);
        if (empty($userGroupInfo)) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "当前分群已经不存在";
            echo json_encode($returnData);
            exit;
        } elseif ($reviserRealName != $userGroupInfo['reviser_real_name']) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = "你不是当前分群的创建者无权操作";
            echo json_encode($returnData);
            exit;
        }

        // 删除具体数据
        try {
            $userTag = new UserTag($userGroupInfo['site_id']);
            $curUserInfo = $userTag->getUserById($id);
            if ($curUserInfo) {
                $email = $curUserInfo['email'];
                $userTag->delUser($userGroupId, $id);

                // 更新具体集合中的数据
                $redis = new RedisMarketingEmail();
                $redis->srem($userTagRedisKey, $email);

                // 更新user_group表中的数据
                $userCount = $redis->scard($userTagRedisKey);
                $userGroup->updateData(['user_count' => $userCount, 'update_time' => time()], $userGroupId, $userGroupInfo['site_id']);
            }
            $returnData['status'] = 0;
            $returnData['errorInfo'] = "success";
            echo json_encode($returnData);
            exit;
        } catch (\Exception $ex) {
            $returnData['status'] = 1;
            $returnData['errorInfo'] = $ex->getMessage();
            echo json_encode($returnData);
            exit;
        }
    }

    /**
     * yumao
     * 2018-5-18
     * 编辑页面相关
     * @return type
     */
    public function actionEbayEdit()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $mothod = strtolower(Yii::$app->request->getMethod());
        $formData = yii::$app->request->$mothod();
        $formData['keyword'] = !empty($formData['keyword']) ? $formData['keyword'] : '';
        $userGroupId = !empty($formData['user_group_id']) ? $formData['user_group_id'] : 0;
        // 获取分群信息
        $userGroup = new UserGroup();

        $userGroupInfo = $userGroup->getUserGroupById($userGroupId, 1);

        if (!$userGroupInfo) {
            $this->sysMsg('警告', '分群已经被删除',
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        } else {

            // 处理数据
            $userGroupInfo['update_time'] = yii::$app->bjTime->date("Y-m-d H:i", $userGroupInfo['update_time']);

            if ($userGroupInfo['update_info']) {
                $userGroupInfo['update_detail'] = json_decode($userGroupInfo['update_info'], true);
                if ($userGroupInfo['update_detail']) {
                    if (!empty($userGroupInfo['update_detail']['importTime'])) {
                        $userGroupInfo['update_detail']['importTime'] = yii::$app->bjTime->date("Y-m-d H:i", $userGroupInfo['update_detail']['importTime']);
                    } else {
                        $userGroupInfo['update_detail']['importTime'] = yii::$app->bjTime->date("Y-m-d H:i", 0);
                    }
                    $defaultPageSize = 20; // 默认条数
                    $page = !empty(Yii::$app->request->$mothod('page')) ? Yii::$app->request->$mothod('page') : 1;
                    $pageSize = !empty(Yii::$app->request->$mothod('pagesize')) ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
                    $formData['page'] = $page;
                    $formData['pageSize'] = $pageSize;
                    $siteId = $userGroupInfo['site_id'];
                    // 查询具体用户数据
                    $userTag = new UserTag($siteId);
                    $userArr = $userTag->getUser($formData);

                    // 处理数据
                    if (!empty($userArr['userInfo'])) {
                        foreach ($userArr['userInfo'] as $userInfoKey => $userInfoVal) {
                            $userArr['userInfo'][$userInfoKey]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($userInfoVal['email']));
                            $userArr['userInfo'][$userInfoKey]['add_time'] = yii::$app->bjTime->date("Y-m-d H:i", $userInfoVal['add_time']);
                        }
                    }
                    // 分页相关
                    $pages = new Pagination(['totalCount' => $userArr['totalCount'], 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
                }
            }
            if (!empty($userArr)) {
                return $this->render("//marketing/user-group/ebay-edit", ["data" => $userGroupInfo, 'pages' => $pages, 'formData' => $formData, 'userArr' => $userArr['userInfo']]);
            } else {
                return $this->render("//marketing/user-group/ebay-edit", ["data" => $userGroupInfo]);
            }
        }
    }


    /**
     * yumao
     * 2018-5-18
     * 编辑页面相关
     * @return type
     */
    public function actionLangriaEdit()
    {
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $mothod = strtolower(Yii::$app->request->getMethod());
        $formData = yii::$app->request->$mothod();
        $formData['keyword'] = !empty($formData['keyword']) ? $formData['keyword'] : '';
        $userGroupId = !empty($formData['user_group_id']) ? $formData['user_group_id'] : 0;
        // 获取分群信息
        $userGroup = new UserGroup();

        $userGroupInfo = $userGroup->getUserGroupById($userGroupId, 1);

        if (!$userGroupInfo) {
            $this->sysMsg('警告', '分群已经被删除',
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        } else {

            // 处理数据
            $userGroupInfo['update_time'] = yii::$app->bjTime->date("Y-m-d H:i", $userGroupInfo['update_time']);

            if ($userGroupInfo['update_info']) {
                $userGroupInfo['update_detail'] = json_decode($userGroupInfo['update_info'], true);
                if ($userGroupInfo['update_detail']) {
                    if (!empty($userGroupInfo['update_detail']['importTime'])) {
                        $userGroupInfo['update_detail']['importTime'] = yii::$app->bjTime->date("Y-m-d H:i", $userGroupInfo['update_detail']['importTime']);
                    } else {
                        $userGroupInfo['update_detail']['importTime'] = yii::$app->bjTime->date("Y-m-d H:i", 0);
                    }
                    $defaultPageSize = 20; // 默认条数
                    $page = !empty(Yii::$app->request->$mothod('page')) ? Yii::$app->request->$mothod('page') : 1;
                    $pageSize = !empty(Yii::$app->request->$mothod('pagesize')) ? Yii::$app->request->$mothod('pagesize') : $defaultPageSize;
                    $formData['page'] = $page;
                    $formData['pageSize'] = $pageSize;
                    $siteId = $userGroupInfo['site_id'];
                    // 查询具体用户数据
                    $userTag = new UserTag($siteId);
                    $userArr = $userTag->getUser($formData);

                    // 处理数据
                    if (!empty($userArr['userInfo'])) {
                        foreach ($userArr['userInfo'] as $userInfoKey => $userInfoVal) {
                            $userArr['userInfo'][$userInfoKey]['email'] = Yii::$app->email->emailDispProcess(Yii::$app->emailmarket->decryption($userInfoVal['email']));
                            $userArr['userInfo'][$userInfoKey]['add_time'] = yii::$app->bjTime->date("Y-m-d H:i", $userInfoVal['add_time']);
                        }
                    }
                    // 分页相关
                    $pages = new Pagination(['totalCount' => $userArr['totalCount'], 'pageSize' => $pageSize, 'defaultPageSize' => $pageSize]);
                }
            }
            if (!empty($userArr)) {
                return $this->render("//marketing/user-group/langria-edit", ["data" => $userGroupInfo, 'pages' => $pages, 'formData' => $formData, 'userArr' => $userArr['userInfo']]);
            } else {
                return $this->render("//marketing/user-group/langria-edit", ["data" => $userGroupInfo]);
            }
        }
    }


    /*
     * 异步获取国家数据
     */
    public function actionGetRegion()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id");
        if ($siteId) {
            $userGroupModel = new UserGroup();
            $returnData = $userGroupModel->getRegion($siteId);
            $this->returnJson(0, "success", $returnData);
        }

    }

    /**
     * 添加分群
     * @return string
     */
    public function actionAdd()
    {

        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $site_id = yii::$app->request->$method('site_id');
        $site = Yii::$app->request->$method('site');
        $type = Yii::$app->request->$method('type');

        $defaultIndex = Yii::$app->request->$method('source');
        $defaultIndex = (empty($defaultIndex)) ? "ALL" : $defaultIndex;
        $site_id = intval($site_id);
        if (!$site_id) {
            $this->sysMsg('警告', '网站ID不存在!',
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        }

        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();

        // 获取某一网站的一级品类信息
        $cateGoryInfo = [];
        $category = new Category();
        if ($site_id == 25) {
            $cateGoryInfo = $category->getCategoryInfoUnlimit($site_id);
        } else {
            $cateGoryInfo = $category->getCategoryInfo($site_id);
        }

        $cateGoryInfoTmp = [];
        $cateGoryInfoTmp[0] = '--选择一级品类--';

        if ($site_id == 25) {

            if (!empty($cateGoryInfo)) {
                foreach ($cateGoryInfo as $cateGoryInfoKey => $cateGoryInfoVal) {
                    $cateGoryInfoTmp[$cateGoryInfoVal['id']] = $cateGoryInfoVal['name_en'];
                }
                $cateGoryInfo = $cateGoryInfoTmp;
            }

        } elseif ($site_id == 12 || $site_id == 11) {
            foreach ($cateGoryInfo as $cateGoryInfoVal) {
                $cateGoryInfoTmp[$cateGoryInfoVal['category_id']] = $cateGoryInfoVal['category_name'];
            }
            $cateGoryInfo = $cateGoryInfoTmp;
        }
        if (!empty($site_id)) {
            $regSource = TemplateMarket::regSourceList($site_id);
        } else {
            //$regSource= [];
            $regSource = ['ALL' => '全站'];
        }
        return $this->render("//marketing/user-group/add", ["data" => $accessSiteInfo,
            "site_id" => $site_id, 'cateGoryInfo' => $cateGoryInfo, 'regSource' => $regSource, 'defualtIndex' => $defaultIndex, 'site' => $site]);
    }

    /**
     * 注册来源列表
     * author xianxuefeng
     * date 2018/4/26
     */
    public function actionRegSourceList()
    {
        $method = yii::$app->request->getMethod();
        $site_id = yii::$app->request->$method('site_id');
        $regSourceParam = yii::$app->request->$method("reg_source");

        $formData['reg_source'] = isset($regSourceParam) ? $regSourceParam : 'ALL';
        $site_id = intval($site_id);
        if (!$site_id) {
            $this->sysMsg('警告', '网站ID不存在!',
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        }

        if (!empty($site_id)) {
            $regSourceInfo = TemplateMarket::regSourceList($site_id);
        } else {
            $regSourceInfo = ['ALL' => '全站'];
            //$regSourceInfo = [];
        }
        $regSource = Html::dropDownList('reg_source',
            'ALL', $regSourceInfo, ['class' => 'form-control z-select mr10 mb5']);

        $return = array(
            'status' => 1,
            'datas' => $regSource,
            // 'display' => empty($regSourceInfo) ? false :true
        );
        echo json_encode($return);
        exit;
    }

    /**
     * 分群添加确认
     */
    public function actionDoAdd()
    {
        ini_set('memory_limit', '1024M');

        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();

        $formData['user_behavior_category_id_info'] = [];

        if ($formData['site_id'] == 12) {

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && isset($formData['browse' . $i]) && $formData['category_id' . $i] && $formData['browse' . $i]) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i], 'user_behavor' => $formData['browse' . $i]];
                }
            }
        }
//        var_dump($formData['user_behavior_category_id_info']);exit;
        if ($formData['site_id'] == 11) {    //gb 和 rg 组合规则

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && !empty($formData['category_id' . $i])) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i]];
                }
            }
        }

        if ($formData['site_id'] == 25) {   //只获自动同步用户信息
            $formData['import_type'] = 0;
        }

        if (!empty($formData['categoryData'])) {
            if ($formData['site_id'] == 25) {
                $formData['category_id_info'] = $this->dealCategoryIdUnlimit($formData);
            }
        }

        $verify = $this->verifyAddData($formData);
        if (true !== $verify) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilege($formData['site_id']);    // 校验用户是否具有站点的权限
        $data = $this->getAddData($formData);
        $session = Yii::$app->session;

        /*
        * Reason  添加渠道筛选，国家编码
        * Author xianxuefeng
        * Date 2018/4/27
        * Explain: 渠道来源为空时，默认ALL,全站
        */
        $regSourceCon = [];
        if (isset($formData['reg_source']) && (!empty($formData['reg_source']) && $formData['reg_source'] != "ALL")) {
            $regSourceCon = ['reg_source' => $formData['reg_source']];
            $data['reg_source'] = $formData['reg_source'];
        }
        $data['reviser_real_name'] = $session['admin_info']['real_name'];
        $data['user_group_type'] = 1;
        $data['is_sys'] = 0;

        // 获取用户数
        $regCon = json_decode($data['reg_con'], true);
        $loginCon = json_decode($data['login_con'], true);
        $orderCon = json_decode($data['order_con'], true);
        $mailCon = json_decode($data['mail_con'], true);
        $cateCon = json_decode($data['cate_con'], true);
        $userBehaviorCateCon = json_decode($data['user_behavior_cate_con'], true);

//        if ($formData['site_id']== 11 && $formData['order_state'] == 2) {    // rg 且已支付订单
//            $rgPaidOrderInfo['shop_num_min'] = $formData['shop_num_min'];
//            $rgPaidOrderInfo['shop_num_max'] = $formData['shop_num_max'];
//            $rgPaidOrderInfo['pay_money_min'] = $formData['pay_money_min'];
//            $rgPaidOrderInfo['pay_money_max'] = $formData['pay_money_max'];
//            $rgPaidOrderInfo['order_near_days'] = $formData['order_near_days'];
//            $userBehaviorCateCon['rg_order_con'] =$rgPaidOrderInfo;
//            $data['user_behavior_cate_con'] = \GuzzleHttp\json_encode($userBehaviorCateCon);
//        }

        $userLabelCon = json_decode($data['user_label_con'], true);

        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
        if (!empty($siteInfo['accessEs'])) {
            $summaryInfo = $userGroupModel->getCountEs($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon, $cateCon, $userLabelCon, $regSourceCon, $userBehaviorCateCon);

            $summaryCount = $summaryInfo['count'];

            $data['es_filters'] = $summaryInfo['es_filters'];

        } else {
            $summaryCount = $userGroupModel->getCount($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon, $cateCon, $userBehaviorCateCon, $userLabelCon, $regSourceCon);
        }
        $data['user_count'] = $summaryCount;
        $data['update_time'] = time();
        $data['use_time'] = time();

        // 添加到数据库
        $userGroupModel = new UserGroup();
        $userGroupModel->addUserGroup($data);
        $this->returnJson(0, "success");
    }

    /**
     * 验证添加分群数据
     * @param $formData
     * @return bool|string
     */
    private function verifyAddData($formData)
    {
        if (empty($formData['site_id'])) {
            return [10008, "请选择站点"];
        }
        if (empty($formData['user_group_name'])) {
            return [10009, "请填写分群名称"];
        }
        if (!isset($formData['user_group_id'])) {
            return [10010, "不存在分群id"];
        }

        if (!isset($formData['register_state']) && !isset($formData['login_state']) && !isset($formData['order_state']) && !isset($formData['mail_state']) && !isset($formData['category_id1']) && !isset($formData['userLabel'])) {
            return [10011, "数据不完整"];
        }
        if (empty($formData['register_state']) && empty($formData['login_state'])
            && empty($formData['order_state']) && empty($formData['mail_state']) && empty($formData['userLabel']) && empty($formData['category_id1'])
        ) {
            return [10011, "数据不完整"];
        }

        /*
        if (!isset($formData['register_state'], $formData['login_state'])
            || !isset($formData['order_state'], $formData['mail_state'])
        ) {
            return [10011, "数据不完整"];
        }
        if (empty($formData['register_state']) && empty($formData['login_state'])
            && empty($formData['order_state']) && empty($formData['mail_state'])
        ) {
            return [10011, "数据不完整"];
        }
        */

        $isDup = $this->isDuplicate($formData['site_id'], $formData['user_group_name'], $formData['user_group_id']);
        if ($isDup) {
            return [10012, "分群名称重复"];
        }

        return true;
    }

    /**
     * 获取添加分群的数据
     * @param $formData
     * @return mixed
     */
    private function getAddData($formData)
    {
        $data['site_id'] = $formData['site_id'];
        $data['user_group_name'] = $formData['user_group_name'];
        $data['description'] = $formData['description'];
        $data['form_data'] = json_encode($formData);

        $freqArr = [
            "1" => ["equal_frequency" => 1],
            "2" => ["min_frequency" => 2, "max_frequency" => 4],
            "3" => ["min_frequency" => 5, "max_frequency" => 7],
            "4" => ["min_frequency" => 8, "max_frequency" => 9],
            "5" => ["min_frequency" => 10]
        ];

        $orderMoneyArr = [
            "1" => ["min_money" => 0, "max_money" => 50],
            "2" => ["min_money" => 50, "max_money" => 100],
            "3" => ["min_money" => 100, "max_money" => 200],
            "4" => ["min_money" => 200, "max_money" => 300],
            "5" => ["min_money" => 300, "max_money" => 500],
            "6" => ["min_money" => 500],
        ];

        // 注册相关条件
        $regCon['state'] = $formData['register_state'];
        if (1 == $formData['register_time_type']) {     // 指定近几天
            if (!empty($formData['register_near_days'])) {
                $regCon['near_days'] = $formData['register_near_days'];
            }
        } else {                                // 指定时间区间
            if (!empty($formData['register_start_time'])) {
                $regCon['start_time'] = yii::$app->bjTime->strtotime($formData['register_start_time']);
            }
            if (!empty($formData['register_end_time'])) {
                $regCon['end_time'] = yii::$app->bjTime->strtotime($formData['register_end_time']);
            }
        }

        // 登录相关条件
        $loginCon['state'] = $formData['login_state'];
        if (1 == $formData['login_time_type']) {        // 指定近几天
            if (!empty($formData['login_near_days'])) {
                $loginCon['near_days'] = $formData['login_near_days'];
            }
        } else {            // 指定时间区间
            if (!empty($formData['login_start_time'])) {
                $loginCon['start_time'] = yii::$app->bjTime->strtotime($formData['login_start_time']);
            }
            if (!empty($formData['login_end_time'])) {
                $loginCon['end_time'] = yii::$app->bjTime->strtotime($formData['login_end_time']);
            }
        }
        // 登录频次条件
        if (isset($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['login_frequency']] as $freqKey => $freqValue) {
                $loginCon[$freqKey] = $freqValue;
            }
        }

        // 下单相关条件
        $orderCon['state'] = $formData['order_state'];
        if (1 == $formData['order_time_type']) {    // 指定近几天
            if (!empty($formData['order_near_days'])) {
                $orderCon['near_days'] = $formData['order_near_days'];
            }
        } else {                // 指定时间区间
            if (!empty($formData['order_start_time'])) {
                $orderCon['start_time'] = yii::$app->bjTime->strtotime($formData['order_start_time']);
            }
            if (!empty($formData['order_end_time'])) {
                $orderCon['end_time'] = yii::$app->bjTime->strtotime($formData['order_end_time']);
            }
        }
        // 下单频次条件
        if (isset($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['order_frequency']] as $freqKey => $freqValue) {
                $orderCon[$freqKey] = $freqValue;
            }
        }

        // 下单金额
        if (isset($formData['order_money']) && key_exists($formData['order_money'], $orderMoneyArr)) {
            foreach ($orderMoneyArr[$formData['order_money']] as $orderMoneyKey => $orderMoneyValue) {
                $orderCon[$orderMoneyKey] = $orderMoneyValue;
            }
        }

        // 邮件行为
        $mailCon['state'] = $formData['mail_state'];
        if (1 == $formData['mail_time_type']) {     // 指定近几天
            if (!empty($formData['mail_near_days'])) {
                $mailCon['near_days'] = $formData['mail_near_days'];
            }
        } else {        // 指定时间区间
            if (!empty($formData['mail_start_time'])) {
                $mailCon['start_time'] = yii::$app->bjTime->strtotime($formData['mail_start_time']);
            }
            if (!empty($formData['mail_end_time'])) {
                $mailCon['end_time'] = yii::$app->bjTime->strtotime($formData['mail_end_time']);
            }
        }
        // 邮件打开频次
        if (isset($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['mail_open_frequency']] as $freqKey => $freqValue) {
                if ($freqKey == "min_frequency") {
                    $freqKey = "min_open_frequency";
                } else if ($freqKey == "equal_frequency") {
                    $freqKey = "equal_open_frequency";
                } else if ($freqKey == "max_frequency") {
                    $freqKey = "max_open_frequency";
                } else {
                    // do nothing
                }
                $mailCon[$freqKey] = $freqValue;
            }
        }
        // 邮件点击频次
        if (isset($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqArr)) {
            foreach ($freqArr[$formData['mail_click_frequency']] as $freqKey => $freqValue) {
                if ($freqKey == "min_frequency") {
                    $freqKey = "min_click_frequency";
                } else if ($freqKey == "equal_frequency") {
                    $freqKey = "equal_click_frequency";
                } else if ($freqKey == "max_frequency") {
                    $freqKey = "max_click_frequency";
                } else {
                    // do nothing
                }
                $mailCon[$freqKey] = $freqValue;
            }
        }

        // 品类条件相关(单级)
        $categoryCon = $userBehaviorCateCon = [];

        $categoryCon['relation'] = !empty($formData['relation']) ? intval($formData['relation']) : 0;

        // (单级)
        if ($data['site_id'] == 12 || $data['site_id'] == 11) {   // GB 评论条件和RG品类条件
            if (isset($formData['user_behavior_category_id_info']) && $formData['user_behavior_category_id_info']) {
                $userBehaviorCateCon['relation'] = $categoryCon['relation'];
                $userBehaviorCateCon['user_behavior_category_id'] = $formData['user_behavior_category_id_info'];
            }

            if ($formData['site_id']== 11 && $formData['order_state'] == 2  && (
                     ! empty($formData['shop_num_min']) ||
                        ! empty($formData['shop_num_max']) ||
                        ! empty($formData['pay_money_min']) ||
                        ! empty($formData['pay_money_max']) || ($formData['order_state'] == 2 && ! empty($formData['category_id1']))
                     )) {    // rg 且已支付订单
                $rgPaidOrderInfo['shop_num_min'] = $formData['shop_num_min'];
                $rgPaidOrderInfo['shop_num_max'] = $formData['shop_num_max'];
                $rgPaidOrderInfo['pay_money_min'] = $formData['pay_money_min'];
                $rgPaidOrderInfo['pay_money_max'] = $formData['pay_money_max'];
                $rgPaidOrderInfo['order_near_days'] = $formData['order_near_days'];
                $userBehaviorCateCon['rg_order_con'] = $rgPaidOrderInfo;
                //  $data['user_behavior_cate_con'] = \GuzzleHttp\json_encode($userBehaviorCateCon);
            }
        } else {
            if (isset($formData['category_id']) && is_array($formData['category_id']))
                foreach ($formData['category_id'] as $catgoryId) {
                    if (!empty($catgoryId)) {
                        $categoryCon['category_id'][] = $catgoryId;
                    }
                }
        }

        // (多级)(如果有多级品类则不需要考虑单级品类)
        if (isset($formData['category_id_info']) && is_array($formData['category_id_info'])) {
            $categoryCon['category_id'] = [];
            foreach ($formData['category_id_info'] as $categoryIdInfoVal) {
                if (!empty($categoryIdInfoVal)) {
                    $categoryTempStr = "";
                    foreach ($categoryIdInfoVal as $categoryIdCur) {
                        $categoryTempStr .= $categoryIdCur . "/";
                    }
                    if (!empty($categoryTempStr)) {
                        $categoryCon['category_id'][] = "/" . trim($categoryTempStr, "/") . "/";
                    }
                }
            }
        }

        //crm 用户标签相关
        $userlabelCon = [];
        if (!empty($formData['userLabel'])) {
            $userlabelCon['queue_id'] = $formData['userLabel'];
        }

        $data['reg_con'] = json_encode($regCon);
        $data['login_con'] = json_encode($loginCon);
        $data['order_con'] = json_encode($orderCon);
        $data['mail_con'] = json_encode($mailCon);
        $data['cate_con'] = json_encode($categoryCon);
        $data['user_behavior_cate_con'] = json_encode($userBehaviorCateCon);
        $data['user_label_con'] = json_encode($userlabelCon);

        return $data;
    }

    /**
     * 编辑分群
     * @return string
     */
    public function actionEdit()
    {
        // 阿拉伯数字转汉字和写对应关系
        $numsToCh = [
            1 => '一',
            2 => '二',
            3 => '三',
            4 => '四',
            5 => '五',
            6 => '六',
            7 => '七',
            8 => '八',
            9 => '九',
            10 => '十',
        ];
        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method("user_group_id");
        $type = yii::$app->request->$method("type");
        if (empty($userGroupId)) {
            $this->sysMsg('警告', "参数不完整",
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        }
        $accessSiteInfo = Yii::$app->authority->getMarketEmailAccessSite();
        $userGroupModel = new UserGroup();
        $group = $userGroupModel->getByCondition(['user_group_id' => $userGroupId]);
        if (empty($group)) {
            $this->sysMsg('警告', "不存在该分群",
                ['type' => 'error', 'links' => [['name' => '返回上一页', 'url' => 'javascript:history.go(-1)']]]);
        }
        $formData = json_decode($group[0]['form_data'], true);


        $data = $formData;

        if (!empty($data['categoryData'])) {
            $categoryDataParentIdArr = [];
            $categoryDataTempParentIdArr = [];

            $categoryDataTempIdArr = [];
            $categoryDataIdArr = []; // 所有有用户数据的同级id值

            $data['categoryData'] = json_decode($data['categoryData'], true);

            if (empty($data['categoryData'])) {
                $data['categoryData'] = [];
            }
            foreach ($data['categoryData'] as $categoryDataKey => $categoryDataVal) {  // 获取所有分类id值，为了获取所有有数据的同级别信息
                foreach ($categoryDataVal['data'] as $categoryDataValData) {
                    if ($categoryDataValData['value'] != 0) {
                        $categoryDataTempIdArr[$categoryDataValData['value']] = $categoryDataValData['value'];
                    }

                }

            }
            $categoryDataTempIdStr = join(',', $categoryDataTempIdArr);

            if (empty($categoryDataTempIdStr)) {
                $categoryDataTempIdStr = "0";
            } else {
                $categoryDataTempIdStr .= ",0";
            }
            // 查询相关分类的父分类
            $parentIdSql = "select id,parent_id,level from lr_category where id in ({$categoryDataTempIdStr})";
            $parentIdInfo = yii::$app->db->createCommand($parentIdSql)->queryAll();

            $parentIdInfoDeal = [];
            $parentIdInfoRelation = [];
            $parentIdInfoStr = "";
            $parentIdArr = [];
            foreach ($parentIdInfo as $parentIdInfoVal) {
                $parentIdInfoDeal[$parentIdInfoVal['id']] = $parentIdInfoVal;
                $parentIdArr[] = $parentIdInfoVal['parent_id'];
                $parentIdArr[] = $parentIdInfoVal['id'];
            }

            $parentIdInfoStr = join(',', $parentIdArr);
            if (empty($parentIdInfoStr)) {
                $parentIdInfoStr = "0";
            }
            $siblingCategoryInfo = [];
            $siblingCategoryInfoDeal = [];
            $siblingCategoryInfoDealDeal = [];
            $category = new Category();
            $siblingCategoryInfo = $category->getCategoryInfoUnlimitByStr(25, $parentIdInfoStr);


            // 遍历处理数据
            foreach ($siblingCategoryInfo as $siblingCategoryInfoVal) {
                $siblingCategoryInfoDeal[$siblingCategoryInfoVal['parent_id']][] = $siblingCategoryInfoVal;

            }

            // 遍历处理数据（处理父分类id和当前分类id对应关系）

            // 组装相关数据(把名称，相关的平级信息组装上)
            // echo '<pre>';
            // var_dump($data['categoryData']);
            // exit;

            foreach ($data['categoryData'] as $categoryDataKey => $categoryDataVal) {
                foreach ($categoryDataVal['data'] as $categoryDataValKey => $categoryDataValVal) {


                    // echo '<pre>';
                    // var_dump($parentIdInfoDeal[$categoryDataValVal['value']]);

                    // 先找到当前父分类id值
                    if ($categoryDataValVal['value'] != 0) {
                        $parentIdTmp = $parentIdInfoDeal[$categoryDataValVal['value']]['parent_id'];


                        $curLevel = $parentIdInfoDeal[$categoryDataValVal['value']]['level'];
                        $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['level'] = $curLevel;
                        $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['levelName'] = "--选择" . $numsToCh[$curLevel] . '级分类--';
                        // 根据父分类id找到同级信息
                        $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['siblingCategoryInfo'] = $siblingCategoryInfoDeal[$parentIdTmp];
                    } else {

                        if (!empty($categoryDataVal['data'][$categoryDataValKey - 1]) && !empty($categoryDataVal['data'][$categoryDataValKey - 1]['value'])) {

                            $parentIdTmp = $categoryDataVal['data'][$categoryDataValKey - 1]['value'];

                            $curLevel = $parentIdInfoDeal[$parentIdTmp]['level'] + 1;

                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['level'] = $curLevel;
                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['levelName'] = "--选择" . $numsToCh[$curLevel] . '级分类--';

                            // 根据父分类id找到同级信息
                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['siblingCategoryInfo'] = $siblingCategoryInfoDeal[$parentIdTmp];
                        } else {
                            $parentIdTmp = 0;
                            $curLevel = 1;
                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['level'] = $curLevel;
                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['levelName'] = "--选择" . $numsToCh[$curLevel] . '级分类--';
                            $data['categoryData'][$categoryDataKey]['data'][$categoryDataValKey]['siblingCategoryInfo'] = $siblingCategoryInfoDeal[0];
                        }

                    }
                }
            }

        }

        /**
         *  rg 品类
         *  author xianxuefeng
         *  date  2018/8/3
         * [[['category_id' => 1,'category_name' => '','defualt_cate'=>'']]]
         */
        if (isset($data['site_id']) && $data['site_id'] == 11) {    //rg 品类
            $data['categoryLevel'] = $this->getRbCatetion($data);
        }

        $allCateByGradeArr = $allCateArr = [];
        $category = new Category();

        if (isset($data['user_behavior_category_id_info']) && $data['user_behavior_category_id_info']) {
            $data['gb_category'] = $category->getCategoryInfo($data['site_id'], 0, 1);

            foreach ($data['gb_category'] as $cate) {
                $allCateByGradeArr[$cate['category_grade']][$cate['category_id']] = $cate['category_name'];
                $allCateArr[$cate['category_id']]['parent'] = $cate['parent_id'];
                $allCateArr[$cate['category_id']]['category_grade'] = $cate['category_grade'];
            }
//            var_dump($allCateArr);exit;
            foreach ($data['user_behavior_category_id_info'] as $key => $userBehaviors) {
                $allCateParentArr = [];
                if (isset($allCateArr[$userBehaviors['min_category_id']]) && $allCateArr[$userBehaviors['min_category_id']]['parent'] > 0) {
                    $grade = $allCateArr[$userBehaviors['min_category_id']]['category_grade'];
                    $allCateParentArr[$grade] = $userBehaviors['min_category_id'];
                    $this->getCateParentIds($allCateArr, $allCateArr[$userBehaviors['min_category_id']]['parent'], $allCateParentArr, $grade);
                } else if (isset($allCateArr[$userBehaviors['min_category_id']])) {
                    $allCateParentArr[1] = $userBehaviors['min_category_id'];
                }
                $data['user_behavior_category_id_info'][$key]['parent_relation'] = array_reverse($allCateParentArr, true);
            }

            $data['gb_category_all'] = $allCateByGradeArr;
        } else {
            $data['gb_category'] = $category->getCategoryInfo($data['site_id']);
        }


        $data['user_group_id'] = $group[0]['user_group_id'];
        $data['num_china'] = $numsToCh;

        if (isset($data['site_id']) && !empty($data['site_id']) && $data['site_id'] == 12) {   //site_id =12 是gearbest
            $regSource = TemplateMarket::regSourceList($data['site_id']);
        } else {
            //$regSource= [];
            $regSource = [];
        }
        // echo "<pre/>";
        // print_r($data);die;
        //rg 品类
        return $this->render("//marketing/user-group/edit",
            ["data" => $data, "siteInfo" => $accessSiteInfo, 'regSource' => $regSource, 'type' => $type]);
    }

    /**
     * 获取品类分群信息
     * site_id
     * user_bebavior_category_id_info = [["min_category_id"=>"382"]]
     * @author xianxuefeng
     * @date 2018-08-3
     * @return [[['category_id' => 1,'category_name' => '','defualt_cate'=>'']]]
     */

    public function getRbCatetion($data)
    {
        $numsToCh = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
        //"--选择" . $numsToCh[1] . '级分类--';
        $res = [[[['category_id' => 0, 'category_name' => '--选择一级分类--', 'defualt_cate' => 0]]]];
        $firstLevel = [['category_id' => 0, 'category_name' => '--选择一级分类--', 'defualt_cate' => 0]];
        $Ydb = Yii::$app->db;
        $query = new \yii\db\Query();
        $cond = ['and', 'parent_id=0', 'is_leaves=0'];
        $firstCategory = $query->select(['category_id', 'category_name'])->from('rosegal_category_data')->where($cond)->all($Ydb);
        $firstCategory = array_merge($firstLevel, $firstCategory);
        $res[0][0] = $firstCategory;
        foreach ($res[0][0] as & $v) {
            $v['defualt_cate'] = 0;                      //赋值默认值
        }
        $res[0][0][0]['defualt_cate'] = 1;

        if (empty($data['user_behavior_category_id_info'])) {
//            $res[0][0][0]['defualt_cate'] =1;
            return $res;
        }
        $categoryList = $data['user_behavior_category_id_info'];

        //简化最小品类数组层级
        $categoryArr = [];
        foreach ($categoryList as $val) {
            $categoryArr[] = $val['min_category_id'];
        }
        //获取rg的一级品类
//        $Ydb        = Yii::$app->db;
//        $query      = new \yii\db\Query();
//        $cond = ['and','parent_id=0','is_leaves=0'];
//
//        $firstCategory = $query->select([ 'category_id','category_name'])->from('rosegal_category_data')->where($cond)->all($Ydb);
//        $firstCategory = array_merge($firstLevel,$firstCategory);
        $response = [];
        $index = -1;

        foreach ($categoryArr as $minCateId) {
            $categroyCond = ['and', "min_category_relation like '%," . $minCateId . ",%'"];
            $minCateIds = $query->select(['min_category_relation'])->from('rosegal_category_data')->where($categroyCond)->scalar($Ydb);
            if (empty($minCateIds)) {    //是空或非数组
                continue;
            }
            $minCateIds = trim($minCateIds, ",");
            //字符串转化为数组
            $minCateArr = explode(',', $minCateIds);
            $tempCate = [];
            foreach ($firstCategory as & $val) {
                $val['defualt_cate'] = 0;                      //赋值默认值
                if ($val['category_id'] == $minCateArr[0]) {  //是否等于一级品类
                    $val['defualt_cate'] = 1;
                }
                $tempCate[] = $val;
            }
            ++$index;
            //第一级品类赋值默认值
            $response[$index][0] = $tempCate;

            if ($minCateArr[0] == $minCateId) {     //层级只有一级时，返回
                continue;
            }
            $level = 1; //分类层级
            //层级大于等于2级时获取其它层级分类的子层级
            foreach ($minCateArr as $key => $parent_id) {    //根据parent_id 获取下级所有子品类
                if ($parent_id == $minCateId) {   //如果父级品类等于最小品类,不需要在获取下级品类信息
                    break;
                }
                $subCategory = $query->select(['category_id', 'category_name'])->from('rosegal_category_data')->where(['and', "parent_id={$parent_id}"])->all($Ydb);
                if (empty($subCategory)) {
                    continue;
                }

                foreach ($subCategory as & $sub) {
                    $sub['defualt_cate'] = 0;
                    if ($sub['category_id'] == $minCateArr[$key + 1]) {  //是否默认展示,层级默认值$minCateArr[$index+1]
                        $sub['defualt_cate'] = 1;
                    }
                }
                $firstLevel[0]['category_name'] = "--选择" . $numsToCh[$level] . '级分类--';
                $subCategory = array_merge($firstLevel, $subCategory);    //添加默认选择
                $response[$index][$level] = $subCategory;
                ++$level;
            }
        }
        // echo "<pre/>";
        // print_r($response);
        // echo count($response);
        // die;
        return $response;
    }


    public function getCateParentIds($allCateArr, $categoryId, &$return, $grade)
    {
        if (isset($allCateArr[$categoryId]) && $allCateArr[$categoryId]['parent'] > 0) {
            $grade--;
            $return[$grade] = $categoryId;
            $this->getCateParentIds($allCateArr, $allCateArr[$categoryId]['parent'], $return, $grade);
        } else if (isset($allCateArr[$categoryId])) {
            $return[1] = $categoryId;
        }
        return;
    }

    /**
     * 编辑分群确认
     */
    public function actionDoEdit()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();

        $formData['user_behavior_category_id_info'] = [];

        if ($formData['site_id'] == 12) {

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && isset($formData['browse' . $i]) && $formData['category_id' . $i] && $formData['browse' . $i]) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i], 'user_behavor' => $formData['browse' . $i]];
                }
            }
        }

        if ($formData['site_id'] == 11) {    //gb 和 rg 组合规则

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && !empty($formData['category_id' . $i])) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i]];
                }
            }
        }

        if (!empty($formData['categoryData'])) {
            if ($formData['site_id'] == 25) {
                $formData['category_id_info'] = $this->dealCategoryIdUnlimit($formData);
            }
        }

        $verify = $this->verifyAddData($formData);
        if (true !== $verify) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilege($formData['site_id']);    // 校验用户是否具有站点的权限
        $data = $this->getAddData($formData);
        $session = Yii::$app->session;

        /*
       * Reason  添加渠道筛选，国家编码
       * Author xianxuefeng
       * Date 2018/4/27
       * Explain: 渠道来源为空时，默认ALL,全站
       */
        $regSourceCon = [];
        if (isset($formData['reg_source']) && (!empty($formData['reg_source']) && $formData['reg_source'] != "ALL")) {
            $regSourceCon = ['reg_source' => $formData['reg_source']];
            $data['reg_source'] = $formData['reg_source'];
        }

        $data['reviser_real_name'] = $session['admin_info']['real_name'];
        $data['user_group_type'] = 1;
        $data['is_sys'] = 0;

        // 获取用户数
        $regCon = json_decode($data['reg_con'], true);
        $loginCon = json_decode($data['login_con'], true);
        $orderCon = json_decode($data['order_con'], true);
        $mailCon = json_decode($data['mail_con'], true);
        $cateCon = json_decode($data['cate_con'], true);
        $userBehaviorCateCon = json_decode($data['user_behavior_cate_con'], true);
        $userLabelCon = json_decode($data['user_label_con'], true);

        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
        if (!empty($siteInfo['accessEs'])) {
            $summaryInfo = $userGroupModel->getCountEs($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon, $cateCon, $userLabelCon, $regSourceCon, $userBehaviorCateCon);
            $summaryCount = $summaryInfo['count'];
            $data['es_filters'] = $summaryInfo['es_filters'];
        } else {
            $summaryCount = $userGroupModel->getCount($siteName, 0, $regCon, $loginCon, $orderCon, $mailCon, $cateCon, $userBehaviorCateCon, $userLabelCon, $regSourceCon);
        }
        $data['user_count'] = $summaryCount;
        $data['update_time'] = time();
        $data['use_time'] = time();

        // 添加到数据库
        $userGroupModel = new UserGroup();
        $userGroupModel->updateByCondition(['user_group_id' => $formData['user_group_id']],
            ["is_del" => 1, "reviser_real_name" => $data['reviser_real_name'], "del_time" => time()]);
        $userGroupModel->addUserGroup($data);

        //$userGroupModel->updateByCondition(['user_group_id' => $formData['user_group_id']], $data);
        $this->returnJson(0, "success");
    }

    /**
     * 删除分群
     */
    public function actionDel()
    {
        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method('user_group_id');
        $userGroupModel = new UserGroup();
        $session = Yii::$app->session;
        $data['del_real_name'] = $session['admin_info']['real_name'];
        $data['del_time'] = time();
        $data['is_del'] = 1;
        try {
            $userGroupModel->updateByCondition(["user_group_id" => $userGroupId], $data);
        } catch (\Exception $e) {
            $this->returnJson(10008, "系统繁忙，请重试", "");
        }

        $this->returnJson(0, "success", "");
    }

    public function actionListData()
    {
        return $this->render("//marketing/user-group/list-data", ["data" => ""]);
    }

    /**
     * 添加队列
     * @return string
     */
    public function actionAddSendQueue()
    {
        set_time_limit(0);
        yii::$app->params['now_addr'] = "用户分群";
        $method = yii::$app->request->getMethod();
        $dataInfo = yii::$app->request->$method();

//        if (isset($dataInfo['site_id']) && $dataInfo['site_id'] == 31) { // ebay相关的另算
//            echo 'yyyyy';
//            exit;
//        } else {
//            $data = $this->getAddSendQueueData();
//            echo '<pre>';
//            var_dump($data);
//            exit;
//            if (is_string($data)) {
//                echo $data;
//                exit();
//            }
//        }
        $importType = 'system';   //系统生成的用户
        if (isset($_REQUEST['importType'])) {
            $importType = $_REQUEST['importType'];
        }
        $data = $this->getAddSendQueueData($importType);

        if (is_string($data)) {
            echo $data;
            exit();
        }
        $userManageMarket = new UserManageMarket();
        $data = $userManageMarket->getSendInfo($data);

        return $this->render('/marketing/user-group/add-send-queue', [
            'data' => $data,
            'importType' => $importType,
        ]);
    }

    /**
     * 获取 添加发送队列 的数据
     * @return string
     * $importType ='manual' 手动导入，system 系统生成
     */
    private function getAddSendQueueData($importType = 'system')
    {
        $method = yii::$app->request->getMethod();
        $data = yii::$app->request->$method();

        if (!isset($data['site_id'])) {
            return "数据不完整";
        }

        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        if (empty($siteName)) {
            return "站点不存在";
        }
        $data['brief_code'] = Site::getInstance()->getBriefCode($data['site_id']);
        if (empty($data['brief_code'])) {
            return "站点没有简码";
        }

        $data['site_name'] = $siteName;

        // 排除分群


        if (isset($data['parent_test_group_id']) && isset($data['type']) && $data['type'] == 'ab_test') {
            $mailGroupModel = new MailGroup();
            $parentTestGroupId = intval($data['parent_test_group_id']);
            $testGroupData = $mailGroupModel->getAbTestMailGroup($parentTestGroupId);
            $data = array_merge($data, $testGroupData);
            $data['child'] = $mailGroupModel->getAbTestChildMailGroup($parentTestGroupId);

            $data['totalSendUserPercent'] = $data['totalChildSendUserNums'] = 0;

            $sumCount = 0;
            foreach ($data['child'] as $key => $child) {
                if ($data['user_count'] > 0) {
                    $curCount = round($data['user_count'] * $child['send_users_percent'] / 100);
                    $sumCount += $curCount;

                    if ($sumCount > $data['user_count']) {
                        $data['child'][$key]['child_users'] = $curCount - ($sumCount - $data['user_count']);
                    } else {
                        $data['child'][$key]['child_users'] = $curCount;
                    }
                } else {
                    $data['child'][$key]['child_users'] = 0;
                }
                $data['totalChildSendUserNums'] += $data['child'][$key]['child_users'];
                $data['totalSendUserPercent'] += $child['send_users_percent'];
            }

            $data['user_define_group'] = json_decode($data['user_define_group'], true);
            $data['sys_group'] = json_decode($data['sys_group'], true);
            $data['exclude_group'] = json_decode($data['exclude_group'], true);
            $data['type'] = 'ab_test';
        } else {

            $data['user_define_group'] = yii::$app->request->$method("user_define_group", []);    // 自定义分群
            $data['sys_group'] = yii::$app->request->$method("sys_group", []);               // 系统分群
            $data['exclude_group'] = yii::$app->request->$method("exclude_group", []);
            // 获取用户
            $userGroupModel = new UserGroup();
            if ($data['site_id'] == 31 || ($data['site_id'] == 25 && $importType == 'manual')) { // ebay的数据先单独处理
                $countDataInfo = $this->MergeTagGroupCount($data['user_define_group'], $data['exclude_group'], $siteName);
                $data['user_count'] = $countDataInfo['data']['count'];
            } else {
                $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
                if (!empty($siteInfo['accessEs'])) {
                    $data['user_count'] = $userGroupModel->getMergeGroupCountEs($siteName, $data['user_define_group'],
                        $data['sys_group'], $data['exclude_group']);
                } else {
                    $data['user_count'] = $userGroupModel->getMergeGroupCount($siteName, $data['user_define_group'],
                        $data['sys_group'], $data['exclude_group']);
                }
            }
            $template = new \app\models\marketing\MailTemplate();
            $data['template'] = $template->getTemplateDetailBySite($data['site_id']);
            $curBjTime = \yii::$app->bjTime->time();
            $curBjDate = \yii::$app->bjTime->date('ymd', $curBjTime);
            foreach ($data["template"] as $key => $value) {
                $data['template'][$key]['group_name_prefix'] = $value['template_type_compaign'];
                if (empty($value['template_type_compaign'])) {     // 如果compaign为空，则使用模板名来作为分组名的前缀
                    $data['template'][$key]['group_name_prefix'] = $value['template_name'];
                }
                $data['template'][$key]['track_code'] = str_replace("{sendTime}", $curBjTime, $value['track_code']);
                $data['template'][$key]['track_code'] = str_replace("{sendDate}", $curBjDate, $data['template'][$key]['track_code']);

                // 如果包含custom_track_code 则要剔除掉
                if (!empty($data['template'][$key]['custom_track_code'])) {
                    $data['template'][$key]['track_code'] = rtrim($data['template'][$key]['track_code'], '&' . $data['template'][$key]['custom_track_code']);
                }
            }
        }
        $data['mail'] = Site::getInstance()->getMailSender($data['site_id']);

        return $data;
    }

    /**
     * ajax异步获取品类信息，无限制级别
     */
    public function actionGetCategoryUnlimitAjax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $formData['parent_id'] = !empty($formData['parent_id']) ? intval($formData['parent_id']) : 0;

        // 阿拉伯数字转汉字和写对应关系
        $numsToCh = [
            2 => '二',
            3 => '三',
            4 => '四',
            5 => '五',
            6 => '六',
            7 => '七',
            8 => '八',
            9 => '九',
            10 => '十',
        ];

        if (empty($formData['site_id'])) {
            if (empty($formData['parent_id'])) {
                echo json_encode([0 => '--选择一级品类--']);
                exit;
            } else {
                echo json_encode([]);
                exit;
            }
        }
        $this->checkSitePrivilegeAjax($formData['site_id']);    // 校验用户是否具有站点的权限
        $cateGoryInfo = [];
        $category = new Category();
        $cateGoryInfo = $category->getCategoryInfoUnlimit($formData['site_id'], $formData['parent_id']);

        if (empty($formData['parent_id'])) {
            array_unshift($cateGoryInfo, '--选择一级品类--');
            $curLevel = 1;
        } else {
            $curLevel = $category->getCategoryLevel($formData['site_id'], $formData['parent_id']);
            if (!empty($cateGoryInfo)) {
                array_unshift($cateGoryInfo, '--选择' . $numsToCh[$curLevel] . '级品类--');
            }
        }
        // echo '<pre>';
        // var_dump($cateGoryInfo);
        // exit;
        $lastDealInfo['level'] = $curLevel;
        $dealCateGoryInfoData = [];
        foreach ($cateGoryInfo as $cateGoryInfoKey => $cateGoryInfoVal) {
            if (isset($cateGoryInfoVal['id']) && isset($cateGoryInfoVal['name_en'])) {
                $dealCateGoryInfoData[$cateGoryInfoVal['id']] = $cateGoryInfoVal['name_en'];
            } else {
                $dealCateGoryInfoData[$cateGoryInfoKey] = $cateGoryInfoVal;
            }
        }

        $lastDealInfo['data'] = $dealCateGoryInfoData;
        echo json_encode($lastDealInfo);
        exit;

    }

    /**
     * ajax异步获取品类信息
     */
    public function actionGetCategoryAjax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();

        $formData['parent_id'] = !empty($formData['parent_id']) ? intval($formData['parent_id']) : 0;
        if (empty($formData['site_id'])) {
            if (empty($formData['parent_id'])) {
                echo json_encode([0 => '--选择一级品类--']);
                exit;
            } else {
                echo json_encode([]);
                exit;
            }
        }
        $this->checkSitePrivilegeAjax($formData['site_id']);    // 校验用户是否具有站点的权限

        if ($formData['site_id'] == 25) {
            $this->actionGetCategoryUnlimitAjax();
        }
        $category = new Category();
        $cateGoryInfo = $category->getCategoryInfo($formData['site_id'], $formData['parent_id']);
        $curLevel = 1;
        if (empty($formData['parent_id'])) {
            array_unshift($cateGoryInfo, '--选择一级品类--');
            $curLevel = 1;
        } else {

            // 查看当前分类是几级分类
            $cateGoryLevel = $category->getCategoryLevel($formData['site_id'], $formData['parent_id']);
            if ($formData['site_id'] == 12 || $formData['site_id'] == 11) {
                $categoryArr = [1 => '--选择一级品类--', 2 => '--选择二级品类--', 3 => '--选择三级品类--', 4 => '--选择四级品类--', 5 => '--选择五级品类--', 6 => '--选择六级品类--', 7 => '--选择七级品类--',
                    8 => '--选择八级品类--', 9 => '--选择九级品类--', 10 => '--选择十级品类--', 11 => '--选择十一级品类--', 12 => '--选择十二级品类--', 13 => '--选择十三级品类--'];
                if ($cateGoryInfo && isset($categoryArr[$cateGoryLevel])) {

                    array_unshift($cateGoryInfo, $categoryArr[$cateGoryLevel]);
                }

            } else {
                if ($cateGoryLevel == 4) {
                    $curLevel = 2;
                    if (!empty($cateGoryInfo)) {
                        array_unshift($cateGoryInfo, '--选择二级品类--');
                    }


                } elseif ($cateGoryLevel == 5) {
                    $curLevel = 3;
                    if (!empty($cateGoryInfo)) {
                        array_unshift($cateGoryInfo, '--选择三级品类--');
                    }
                }
            }
        }

        if ($formData['site_id'] == 12 || $formData['site_id'] == 11) {
            $lastDealInfo['level'] = isset($cateGoryLevel) ? $cateGoryLevel : $curLevel;
            $dealCateGoryInfoData = [];
            foreach ($cateGoryInfo as $cateGoryInfoKey => $cateGoryInfoVal) {
                if (isset($cateGoryInfoVal['category_id']) && isset($cateGoryInfoVal['category_name'])) {
                    $dealCateGoryInfoData[$cateGoryInfoVal['category_id']] = $cateGoryInfoVal['category_name'];
                } else {
                    $dealCateGoryInfoData[$cateGoryInfoKey] = $cateGoryInfoVal;
                }
            }
        } else {
            $lastDealInfo['level'] = $curLevel;
            $dealCateGoryInfoData = [];
            foreach ($cateGoryInfo as $cateGoryInfoKey => $cateGoryInfoVal) {
                if (isset($cateGoryInfoVal['id']) && isset($cateGoryInfoVal['name_en'])) {
                    $dealCateGoryInfoData[$cateGoryInfoVal['id']] = $cateGoryInfoVal['name_en'];
                } else {
                    $dealCateGoryInfoData[$cateGoryInfoKey] = $cateGoryInfoVal;
                }
            }
        }

        $lastDealInfo['data'] = $dealCateGoryInfoData;
        echo json_encode($lastDealInfo);
        exit;

    }

    /**
     * 分群预览
     * * 实际分群预览操作
     * @param $formData
     * @return mixed
     * order_state  1 从未下单, 2 已下单
     * order_near_days 近多少天
     * shop_num_min ~ shop_num_max 商品数量区间
     * pay_money_min ~ pay_money_max 付款金额区间
     * category_id1 最小品类层级对应，品类id. 如第2层最小品类 category_id2= 1
     * relation 品类使用的运算关系 and for relation=1 ,or for relation =2
     * preview-ajax
     */
    public function actionPreviewAjax()
    {
        ini_set('memory_limit', '1024M');

        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $verify = $this->verifyAddData($formData);
        if (true !== $verify && 10012 != $verify[0]) {
            $this->returnJson($verify[0], $verify[1]);
        }

        $this->checkSitePrivilegeAjax($formData['site_id']);    // 校验用户是否具有站点的权限

        // echo '<pre>';
        // var_dump($formData);
        $returnData = $this->doPreview($formData);

        // echo '<pre>';
        // var_dump( $returnData);
        // exit;

        $this->returnJson(0, "success", $returnData);
    }

    private function dealCategoryIdUnlimit($formData)
    {

        $categoryIdInfo = [];
        $categoryIdInfoTmp = [];
        if (!empty($formData['categoryData'])) {
            $formData['categoryData'] = json_decode($formData['categoryData'], true);
            foreach ($formData['categoryData'] as $categoryDataVal) {
                $categoryIdInfoTmp = [];
                $i = 1;
                foreach ($categoryDataVal['data'] as $categoryDataIdInfo) {
                    if (!empty($categoryDataIdInfo['value'])) {
                        $categoryIdInfoTmp['category_id' . $i] = $categoryDataIdInfo['value'];
                    } else {
                        continue;
                    }
                    $i++;
                }
                $categoryIdInfo[] = $categoryIdInfoTmp;
            }
        }
        return $categoryIdInfo;
    }

    /**
     * 处理分类id的相关函数
     */
    private function dealCategoryId($formData)
    {

        $categoryIdInfo = [];
        $categoryIdInfoTmp = [];


        // echo "<pre>";
        // var_dump($formData['category_id']);
        // var_dump($formData['category_id2']);
        // var_dump($formData['category_id3']);


        // echo '<br>-----------------<br>';
        if (!empty($formData['category_id'])) {

            // 先处理相关数据使其摆列完成
            $len = count($formData['category_id']);

            $formData['category_id2_deal'] = [];
            $formData['category_id3_deal'] = [];

            // 定义二级分类不存在或二级分类没有数据时三级分类上移个数
            $k = 0;

            // 定义一级分类没有数据是二级分类上移个数
            $n = 0;
            // var_dump($formData['category_id3'][0]);
            // exit;

            // 定义三级分类不存在时

            for ($j = 0; $j <= $len; $j++) {

                if (!empty($formData['category_id'][$j])) { // 如果一级分类相关数据存在
                    // 查询当前一级分类下是否有二级分类
                    $sqlLevel1 = "select count(*) from lr_category where parent_id = " . $formData['category_id'][$j];
                    $countLevel1 = yii::$app->db->createCommand($sqlLevel1)->queryScalar();
                    if ($countLevel1 == 0) {
                        $formData['category_id2_deal'][$j] = 0;
                        $formData['category_id3_deal'][$j] = 0;
                        $n++;
                        $k++;
                    } else {
                        if (isset($formData['category_id2'][$j - $n]) && $formData['category_id2'][$j - $n] == 0) { // 说明当前一级分类下有二级分类 但是二级分类没有选
                            $formData['category_id2_deal'][$j] = 0; // 这是二级分类为0
                            $k++; // 这是三级分类往上移一位
                            $formData['category_id3_deal'][$j] = 0;

                        } elseif (isset($formData['category_id2'][$j - $n]) && $formData['category_id2'][$j - $n] > 0) { // 有选二级分类 则要判断当前二级分类是否有三级分类数据
                            $formData['category_id2_deal'][$j] = $formData['category_id2'][$j - $n];
                            $sql = "select count(*) from lr_category where parent_id = " . $formData['category_id2'][$j - $n];
                            $count = yii::$app->db->createCommand($sql)->queryScalar();
                            if ($count == 0) { // 说明没有三级分类数据
                                $formData['category_id3_deal'][$j] = 0;
                                $k++;
                            } else {
                                $formData['category_id3_deal'][$j] = $formData['category_id3'][$j - $k];
                            }
                        }
                    }


                }
            }

        }

        // echo '<br>--------------------------<br>';
        // var_dump($formData['category_id2_deal']);
        // var_dump($formData['category_id3_deal']);
        // exit;
        if (!empty($formData['category_id'])) {
            foreach ($formData['category_id'] as $categoryIdKey1 => $categoryIdVal1) {
                if (!empty($categoryIdVal1)) {
                    $categoryIdInfoTmp[$categoryIdKey1]['category_id1'] = $categoryIdVal1;
                }
            }
        }

        if (!empty($formData['category_id2_deal'])) {
            foreach ($formData['category_id2_deal'] as $categoryIdKey2 => $categoryIdVal2) {
                if (!empty($categoryIdVal2)) {
                    $categoryIdInfoTmp[$categoryIdKey2]['category_id2'] = $categoryIdVal2;
                }
            }
        }

        if (!empty($formData['category_id3_deal'])) {
            foreach ($formData['category_id3_deal'] as $categoryIdKey3 => $categoryIdVal3) {
                if (!empty($categoryIdVal3)) {
                    $categoryIdInfoTmp[$categoryIdKey3]['category_id3'] = $categoryIdVal3;
                }
            }
        }


        $categoryIdInfo = $categoryIdInfoTmp;

        return $categoryIdInfo;
    }

    /**
     * 实际分群预览操作
     * @param $formData
     * @return mixed
     * order_state  1 从未下单, 2 已下单
     * order_near_days 近多少天
     * shop_num_min ~ shop_num_max 商品数量区间
     * pay_money_min ~ pay_money_max 付款金额区间
     * category_id1 最小品类层级对应，品类id. 如第2层最小品类 category_id2= 1
     * relation 品类使用的运算关系 and for relation=1 ,or for relation = 2
     */
    private function doPreview($formData)
    {

        $formData['user_behavior_category_id_info'] = [];

        if ($formData['site_id'] == 12) {

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && isset($formData['browse' . $i]) && $formData['category_id' . $i] && $formData['browse' . $i]) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i], 'user_behavor' => $formData['browse' . $i]];
                }
            }
        }

        if ($formData['site_id'] == 11) {    //gb 和 rg 组合规则

            for ($i = 1; $i < 11; $i++) {
                if (isset($formData['category_id' . $i]) && !empty($formData['category_id' . $i])) {
                    $formData['user_behavior_category_id_info'][] = ['min_category_id' => $formData['category_id' . $i]];
                }
            }
        }

        if (!empty($formData['categoryData'])) {
            if ($formData['site_id'] == 25) {
                $formData['category_id_info'] = $this->dealCategoryIdUnlimit($formData);
            }
        }
        $data = $this->getAddData($formData);
        $data['reg_con'] = json_decode($data['reg_con'], true);
        $data['login_con'] = json_decode($data['login_con'], true);
        $data['order_con'] = json_decode($data['order_con'], true);
        $data['user_behavior_cate_con'] = json_decode($data['user_behavior_cate_con'], true);
//        if ($formData['site_id']== 11 && $formData['order_state'] == 2) {    // rg 且已支付订单
//            $rgPaidOrderInfo['shop_num_min'] = $formData['shop_num_min'];
//            $rgPaidOrderInfo['shop_num_max'] = $formData['shop_num_max'];
//            $rgPaidOrderInfo['pay_money_min'] = $formData['pay_money_min'];
//            $rgPaidOrderInfo['pay_money_max'] = $formData['pay_money_max'];
//            $rgPaidOrderInfo['order_near_days'] = $formData['order_near_days'];
//           $data['user_behavior_cate_con']['rg_order_con'] =$rgPaidOrderInfo;
//        }

        $data['mail_con'] = json_decode($data['mail_con'], true);
        $data['cate_con'] = json_decode($data['cate_con'], true);
        $data['user_label_con'] = json_decode($data['user_label_con'], true);


        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);

        /*
        * Reason  添加渠道筛选，国家编码
        * Author xianxuefeng
        * Date 2018/5/8
        * Explain: 渠道来源为空，或者全站时，不筛选
        */
        $regSourceCon = [];
        if (isset($formData['reg_source']) && (!empty($formData['reg_source']) && $formData['reg_source'] != "ALL")) {
            $regSourceCon = ['reg_source' => $formData['reg_source']];
            $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
                $data['login_con'], $data['order_con'], $data['mail_con'], $data['cate_con'], $data['user_behavior_cate_con'], $data['user_label_con'], $regSourceCon);
        } else {
            $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
                $data['login_con'], $data['order_con'], $data['mail_con'], $data['cate_con'], $data['user_behavior_cate_con'], $data['user_label_con']);
        }

//        $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
//                                $data['login_con'], $data['order_con'], $data['mail_con'],$data['cate_con'],$data['user_label_con']);
        $summary = ["name" => "已选分群用户（合并去重）", "count" => $summaryCount];

        $item = $this->getPreviewItem($formData);

        $returnData['summary'] = $summary;
        $returnData['item'] = $item;
        return $returnData;
    }

    /**
     * 获取预览中的选项
     * @param $formData
     * @return array
     */
    public function getPreviewItem($formData)
    {
        $item = [];

        $freqNameArr = [
            "1" => "1次",
            "2" => "2~4次",
            "3" => "5~7次",
            "4" => "8~9次",
            "5" => "10次以上"
        ];
        $orderMoneyArr = [
            "1" => "0$~50$",
            "2" => "50$~100$",
            "3" => "100$~200$",
            "4" => "200$~300$",
            "5" => "300$~500$",
            "6" => '500$以上'
        ];

        // 注册
        if (0 != $formData['register_state']) {
            $regName = "";
            if (1 == $formData['register_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['register_near_days']))) {
                    $regName .= "近{$formData['register_near_days']}天 ";
                }
            } else {
                if (!empty($formData['register_start_time'])) {
                    $regName .= "{$formData['register_start_time']}";
                }
                if (!empty($formData['register_end_time'])) {
                    $regName .= "~{$formData['register_end_time']} ";
                }
            }
            if (1 == $formData['register_state']) {
                $regName .= "未注册";
            } else {
                $regName .= "注册";
            }
            //$regCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'], [], [], []);
            $item[] = ["name" => $regName, "count" => ""];
        }

        // 登录
        if (0 != $formData['login_state']) {
            $name = "";
            if (1 == $formData['login_time_type']) {        // 指定近几天
                if (!empty(is_numeric($formData['login_near_days']))) {
                    $name .= "近{$formData['login_near_days']}天 ";
                }
            } else {
                if (!empty($formData['login_start_time'])) {
                    $name .= "{$formData['login_start_time']}";
                }
                if (!empty($formData['login_end_time'])) {
                    $name .= "~{$formData['login_end_time']} ";
                }
            }
            if (1 == $formData['login_state']) {
                $name .= "从未登录";
            } else {
                $name .= "登录";
            }
            if (!empty($formData['login_frequency']) && key_exists($formData['login_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['login_frequency']]} ";
            }
            //$loginCount = $userGroupModel->getCount($siteName, 0, [], $data['login_con'], [], []);
            $item[] = ["name" => $name, "count" => ""];
        }

        // 下单
        if (0 != $formData['order_state']) {
            $name = "";
            if (1 == $formData['order_time_type']) {    // 指定近几天
                if (!empty(is_numeric($formData['order_near_days']))) {
                    $name .= "近{$formData['order_near_days']}天 ";
                }
            } else {
                if (!empty($formData['order_start_time'])) {
                    $name .= "{$formData['order_start_time']}";
                }
                if (!empty($formData['order_end_time'])) {
                    $name .= "~{$formData['order_end_time']} ";
                }
            }

            if (1 == $formData['order_state']) {
                $name .= "从未下单";
            } else {
                $name .= "下单";
            }

            if (!empty($formData['order_frequency']) && key_exists($formData['order_frequency'], $freqNameArr)) {
                $name .= " {$freqNameArr[$formData['order_frequency']]} ";
            }

            // 下单金额相关
            if (!empty($formData['order_money']) && key_exists($formData['order_money'], $orderMoneyArr)) {
                $name .= " 累计订单金额:{$orderMoneyArr[$formData['order_money']]} ";
            }
            //$orderCount = $userGroupModel->getCount($siteName, 0, [], [], $data['order_con'], []);
            $item[] = ["name" => $name, "count" => ""];
        }


        // RG 已下单
        if ($formData['site_id'] == 11 && 2 == $formData['order_state']) {
            $shop_num_min = empty($formData['shop_num_min']) ? 0 : $formData['shop_num_min'];
            $shop_num_max = empty($formData['shop_num_max']) ? 0 : $formData['shop_num_max'];
            $pay_money_min = empty($formData['pay_money_min']) ? 0 : $formData['pay_money_min'];
            $pay_money_max = empty($formData['pay_money_max']) ? 0 : $formData['pay_money_max'];
            $name = '';
            if (!empty($shop_num_min) || !empty($shop_num_max)) {
                $name .= " 商品数量  {$shop_num_min} ~ {$shop_num_max}件 ";
            }
            if (!empty($pay_money_min) || !empty($pay_money_max)) {
                $name .= " 付款金额 " . '$' . "{$pay_money_min} ~ " . '$' . $pay_money_max;
            }
            if (!empty($name)) {
                $name = " 近{$formData['order_near_days']}天 " . $name;
                $item[] = ["name" => $name, "count" => ""];
            }
        }


        if (0 != $formData['mail_state']) {
            $name = "";
            if (1 == $formData['mail_time_type']) {
                if (!empty(is_numeric($formData['mail_near_days']))) {
                    $name .= "近{$formData['mail_near_days']}天 ";
                }
            } else {
                if (!empty($formData['mail_start_time'])) {
                    $name .= "{$formData['mail_start_time']}";
                }
                if (!empty($formData['mail_end_time'])) {
                    $name .= "~{$formData['mail_end_time']} ";
                }
            }
            $mailStateArr = [1 => "从未发送", 3 => "已发送", 2 => "发送未打开", 4 => "邮件打开", 5 => "打开未点击", 6 => "打开并点击"];
            if (key_exists($formData['mail_state'], $mailStateArr)) {
                $name .= " " . $mailStateArr[$formData['mail_state']];
            }
            if (!empty($formData['mail_open_frequency']) && key_exists($formData['mail_open_frequency'], $freqNameArr)) {
                $name .= " 且打开次数{$freqNameArr[$formData['mail_open_frequency']]} ";
            }
            if (!empty($formData['mail_click_frequency']) && key_exists($formData['mail_click_frequency'], $freqNameArr)) {
                $name .= " 且点击次数{$freqNameArr[$formData['mail_click_frequency']]} ";
            }
            //$mailCount = $userGroupModel->getCount($siteName, 0, [], [], [], $data['mail_con']);
            $item[] = ["name" => $name, "count" => ""];

        }

        // 品类相关
        $category = new Category();
        $selectNameArr = [];
        $selectNameStr = "";

        // 单分类
        if (!empty($formData['relation']) && !empty($formData['category_id']) && is_array($formData['category_id'])) {
            foreach ($formData['category_id'] as $categoryId) {
                if (!empty($categoryId)) {
                    $selectNameTmp = $category->getCateNameById($categoryId, $formData['site_id']);
                    if (!empty($selectNameTmp)) {
                        $selectNameArr[] = $selectNameTmp;
                    }
                }
            }


            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ', $selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ', $selectNameArr);
            }

        }

        // GB多级品类
        $userBehavorCateRelaion = [1 => '浏览', 2 => '收藏', 3 => '加购', 4 => '购买'];
        if (!empty($formData['user_behavior_category_id_info']) && is_array($formData['user_behavior_category_id_info'])) {
            foreach ($formData['user_behavior_category_id_info'] as $categoryId) {
                if (!empty($categoryId)) {
                    $selectNameTmp = $category->getCateNameById($categoryId, $formData['site_id']);
                    if (!empty($selectNameTmp)) {
                        if ($categoryId['user_behavor']) {
                            $userBehavorArr = [];
                            foreach ($categoryId['user_behavor'] as $userBehavor) {
                                $userBehavorArr[] = isset($userBehavorCateRelaion[$userBehavor]) ? $userBehavorCateRelaion[$userBehavor] : '';
                            }
                        }
                        $selectNameArr[] = $selectNameTmp . '[' . join(',', $userBehavorArr) . ']';
                    }
                }
            }


            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ', $selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ', $selectNameArr);
            }

        }
        // 多级分类
        if (!empty($formData['relation']) && !empty($formData['category_id_info']) && is_array($formData['category_id_info'])) {
            $selectNameArr = [];
            $selectNameStr = "";
            $categoryIdArr = [];
            $categoryTempStr = "";
            foreach ($formData['category_id_info'] as $categoryIdInfoVal) {
                if (!empty($categoryIdInfoVal)) {

                    $categoryTempId = 0;

                    $categoryIdInfoValLen = count($categoryIdInfoVal);
                    $categoryTempId = $categoryIdInfoVal['category_id' . $categoryIdInfoValLen];

                    if (!empty($categoryTempId)) {
                        $categoryIdArr[] = $categoryTempId;
                    }
                    // if (!empty($categoryTempStr)) {
                    // $selectNameArr[] = trim($categoryTempStr,"/");
                    // }
                }
            }
            if (!empty($categoryIdArr)) {
                $categoryIdArr = array_unique($categoryIdArr);
            }

            foreach ($categoryIdArr as $categoryIdVal) {
                $categoryTempStr = $category->getCateNameById($categoryIdVal, $formData['site_id']);
                if (!empty($categoryTempStr)) {
                    $selectNameArr[] = $categoryTempStr;
                }
            }
            if ($formData['relation'] == 1) {
                $selectNameStr = join(' <font color="blue">and</font> ', $selectNameArr);
            } else {
                $selectNameStr = join(' <font color="blue">or</font> ', $selectNameArr);
            }
        }


        // RG 多级品类
        if ($formData['site_id'] == 11 && isset($formData['user_behavior_category_id_info'], $formData['relation'])
            && is_array($formData['user_behavior_category_id_info'])) {
            $selectNameArr = [];
            $selectNameStr = "";
            foreach ($formData['user_behavior_category_id_info'] as $categoryId) {
                $selectNameTmp = $category->getRgCateNameById($categoryId, $formData['site_id']);
                if (!empty($selectNameTmp)) {
                    $selectNameArr[] = $selectNameTmp;
                }
            }
            if ($formData['relation'] == 1 && !empty($selectNameArr)) {
                $selectNameStr .= "品类偏好： " . join(' <font color="blue">and</font> ', $selectNameArr);
            }
            if ($formData['relation'] == 2 && !empty($selectNameArr)) {
                $selectNameStr .= "品类偏好： " . join(' <font color="blue">or</font> ', $selectNameArr);
            }
        }

        //用户标签
        if (!empty($formData['userLabel'])) {
            $userLabelInfo = (new UserLabelQueue())->getByQueueId($formData['userLabel']);
            $name = "用户标签组：" . (isset($userLabelInfo['queue_name']) ? $userLabelInfo['queue_name'] : '');
            $item[] = ["name" => $name, "count" => ""];
        }

        if (!empty($selectNameStr)) {
            $item[] = ["name" => $selectNameStr, "count" => ""];
        }
        return $item;
    }

    /**
     * 刷新用户数
     *
     * flash-user-count
     */
    public function actionFlashUserCount()
    {
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method('user_group_id');
        if (empty($userGroupId)) {
            $this->returnJson(10008, "数据不完整，没有提交分群id");
        }

        $userGroupModel = new UserGroup();
        $condition = ["user_group_id" => $userGroupId];
        $group = $userGroupModel->getByCondition($condition);
        if (empty($group)) {
            $this->returnJson(10009, "分群不存在");
        }

        $formData = json_decode($group[0]['form_data'], true);
        $this->checkSitePrivilegeAjax($group[0]['site_id']);    // 校验用户是否具有站点的权限

        $summaryCount = $this->doFlashUserDefineCount($userGroupId, $formData);
        $flashTime = yii::$app->bjTime->date("Y-m-d H:i");
        $this->returnJson(0, "success", ["count" => $summaryCount, 'flash_time' => $flashTime]);
    }

    /**
     * 刷新自定义分群的用户数
     * @param $userGroupId
     * @param $formData
     * @return mixed
     */
    private function doFlashUserDefineCount($userGroupId, $formData)
    {

        $userGroupModel = new UserGroup();
        $data = $this->getAddData($formData);
        $data['reg_con'] = json_decode($data['reg_con'], true);
        $data['login_con'] = json_decode($data['login_con'], true);
        $data['order_con'] = json_decode($data['order_con'], true);
        $data['mail_con'] = json_decode($data['mail_con'], true);
        $data['cate_con'] = json_decode($data['cate_con'], true);
        $data['user_behavior_cate_con'] = json_decode($data['user_behavior_cate_con'], true);

        if ($formData['site_id'] == 11 && $formData['order_state'] == 2) {    // rg 且已支付订单 author xianxuefeng date 2018-08-03
            $rgPaidOrderInfo['shop_num_min'] = $formData['shop_num_min'];
            $rgPaidOrderInfo['shop_num_max'] = $formData['shop_num_max'];
            $rgPaidOrderInfo['pay_money_min'] = $formData['pay_money_min'];
            $rgPaidOrderInfo['pay_money_max'] = $formData['pay_money_max'];
            $rgPaidOrderInfo['order_near_days'] = $formData['order_near_days'];
            $data['user_behavior_cate_con']['rg_order_con'] = $rgPaidOrderInfo;
        }

        $data['user_label_con'] = json_decode($data['user_label_con'], true);

        $siteName = Site::getInstance()->getSiteShortNameById($data['site_id']);
        if (isset($formData['reg_source']) && !empty($formData['reg_source']) && $formData['reg_source'] != 'ALL') {
            $reg_source = ['reg_source' => $formData['reg_source']];
            $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
                $data['login_con'], $data['order_con'], $data['mail_con'], $data['cate_con'], $data['user_behavior_cate_con'], $data['user_label_con'], $reg_source);
        } else {
            $summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
                $data['login_con'], $data['order_con'], $data['mail_con'], $data['cate_con'], $data['user_behavior_cate_con'], $data['user_label_con']);
        }
        /*$summaryCount = $userGroupModel->getCount($siteName, 0, $data['reg_con'],
            $data['login_con'], $data['order_con'], $data['mail_con'],$data['cate_con']);*/
        $userGroupModel->updateByCondition(["user_group_id" => $userGroupId],
            ["user_count" => $summaryCount, "update_time" => time()]);
        return $summaryCount;
    }

    /**
     * 刷新系统分群的用户数
     * @param $userGroupId
     * @param $siteId
     * @param $otherCon
     */
    private function doFlashSysCount($userGroupId, $userGroupType, $siteId, $otherCon)
    {
        $userGroupModel = new UserGroup();
        $siteName = Site::getInstance()->getSiteShortNameById($siteId);
        $summaryCount = $userGroupModel->getSysCount($userGroupId, $userGroupType, $siteName, $otherCon);
        $userGroupModel->updateByCondition(["user_group_id" => $userGroupId],
            ["user_count" => $summaryCount, "update_time" => time()]);
    }

    /**
     * 定时刷新任务
     */
    public function actionFlashCountCron()
    {
        // 忽略用户中断，并且无限时执行
        ignore_user_abort(true);
        set_time_limit(0);

        $userGroupModel = new UserGroup();
        if (!empty($_GET['user_group_id'])) {
            $groupList = $userGroupModel->getByCondition(['is_del' => 0, 'user_group_id' => intval($_GET['user_group_id'])]);
        } elseif (!empty($_GET['site_id'])) {
            $groupList = $userGroupModel->getByCondition(['is_del' => 0, 'site_id' => intval($_GET['site_id'])]);
        } else {
            $groupList = $userGroupModel->getByCondition(['is_del' => 0]);
        }

        $curTime = time();
        $maxIntervalTime = 30 * 86400;  // 最大使用的间隔时间:30天
        foreach ($groupList as $group) {
            if (1 == $group['user_group_type']) {   // 自定义分群
                if ($group['use_time'] - $curTime > $maxIntervalTime) {     // 超过最大间隔时间不用更新
                    continue;
                }
                $formData = json_decode($group['form_data'], true);
                try {
                    $this->doFlashUserDefineCount($group['user_group_id'], $formData);
                } catch (\Exception $e) {
                    echo "刷新user_group_id[{$group['user_group_id']}]失败： " . $e->getMessage() . "<br/>";
                    continue;
                }
            } else {            // 系统分群
                $otherCon = json_decode($group['other_con'], true);
                $this->doFlashSysCount($group['user_group_id'], $group['user_group_type'], $group['site_id'], $otherCon);
            }
        }
        echo "刷新完成";
    }

    private function MergeTagGroupCount($userDefineGroup, $excludeGroup, $siteName = 'ebay')
    {
        if (empty($userDefineGroup) && empty($sysGroup)) {      // 没有给自定义分群、系统分群条件的，直接返回0
            return ['code' => 0, 'msg' => 'success', 'data' => ["count" => 0]];
        }

        $curTime = time();
        $userDefineGroupRedisKey = "usertag_ebay_userdefine_temp_{$curTime}";
        $excludeGroupRedisKey = "usertag_ebay_exclude_temp_{$curTime}";
        $resultGroupRedisKey = "usertag_ebay_result_temp_{$curTime}"; // 差集之后的结果集合
        $userDefinedKeyArr = [];
        $excludeKeyArr = [];
        foreach ($userDefineGroup as $userDefineGroupId) {
            $userDefinedKeyArr[] = "usertag_ebay_{$userDefineGroupId}";
        }

        foreach ($excludeGroup as $excludeGroupId) {
            $excludeKeyArr[] = "usertag_ebay_{$excludeGroupId}";
        }
        $redis = new RedisMarketingEmail();

        if ($userDefinedKeyArr) {
            $userDefinedKeyArrAll = array_merge([$userDefineGroupRedisKey], $userDefinedKeyArr);
            $redis->sunionstore($userDefinedKeyArrAll);
        }

        if ($excludeKeyArr) {
            $excludedKeyArrAll = array_merge([$excludeGroupRedisKey], $excludeKeyArr);
            $redis->sunionstore($excludedKeyArrAll);

            // 获取两个集合的差集
            $resultEnd = $redis->sdiff([$userDefineGroupRedisKey, $excludeGroupRedisKey]);

        } else {
            $resultEnd = $redis->smembers($userDefineGroupRedisKey);
        }

        $userGroupModel = new UserGroup();
//        $count = $userGroupModel->getTagMergeGroupCount('ebay',$resultEnd);
        $count = $userGroupModel->getTagMergeGroupCount($siteName, $resultEnd);
        return ['code' => 0, 'msg' => 'success', 'data' => ["count" => $count]];
    }

    /**
     * 合并第三方导入分群相关
     * yumao
     * 2018-5-22
     */
    public function actionMergeTagGroupCount()
    {
        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id", 0);
        $userDefineGroup = yii::$app->request->$method("user_define_group", []);    // 自定义分群
        $excludeGroup = yii::$app->request->$method("exclude_group", []);       // 排除分群

        $siteName = Site::getInstance()->getSiteShortNameById($siteId);
        $returnInfo = $this->MergeTagGroupCount($userDefineGroup, $excludeGroup, $siteName);              //添加
        echo json_encode($returnInfo);
    }

    /**
     * 获取合并分群的用户数
     *
     * merge-group-count
     */
    public function actionMergeGroupCount()
    {
        ini_set('memory_limit', '1024M');

        $method = yii::$app->request->getMethod();
        $siteId = yii::$app->request->$method("site_id", 0);
        $userDefineGroup = yii::$app->request->$method("user_define_group", []);    // 自定义分群
        $sysGroup = yii::$app->request->$method("sys_group", []);               // 系统分群
        $excludeGroup = yii::$app->request->$method("exclude_group", []);       // 排除分群

        $siteName = Site::getInstance()->getSiteShortNameById($siteId);
        if (empty($siteName)) {
            $this->returnJson(10008, "站点不存在", []);
        }

        if (empty($userDefineGroup) && empty($sysGroup)) {      // 没有给自定义分群、系统分群条件的，直接返回0
            $this->returnJson(0, "success", ["count" => 0]);
        }
        $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
        if (!empty($siteInfo['accessEs'])) {
            $userGroupModel = new UserGroup();
            $count = $userGroupModel->getMergeGroupCountEs($siteName, $userDefineGroup, $sysGroup, $excludeGroup);
            $this->returnJson(0, "success", ["count" => $count]);
        }
        $crmUserDefineGroupIds = array_merge($userDefineGroup, $excludeGroup);
        /*
        if(!empty($crmUserDefineGroupIds)){
            $crmUserDefineGroupIdsStr = join(",", $crmUserDefineGroupIds);
            $crmUserDefineGroupIdsSql = "select count(*) from user_group where user_group_id in ($crmUserDefineGroupIdsStr) AND (user_label_con != '' AND user_label_con != '[]')";
            $crmUserDefineGroupIdsNum = yii::$app->db->createCommand($crmUserDefineGroupIdsSql)->queryScalar();
            if($crmUserDefineGroupIdsNum >=2 ){
                $this->returnJson(10008, "不可以选择多个 CRM 标签", []);
            }
        }

        if(!empty($excludeGroup)){
            $crmExcludeGroupGroupIdsStr = join(",", $excludeGroup);
            $crmExcludeGroupGroupIdsSql = "select count(*) from user_group where user_group_id in ($crmExcludeGroupGroupIdsStr) AND (user_label_con != '' AND user_label_con != '[]')";
            $crmExcludeGroupGroupIdsNum = yii::$app->db->createCommand($crmExcludeGroupGroupIdsSql)->queryScalar();
            if($crmExcludeGroupGroupIdsNum >=1 ){
                $this->returnJson(10008, "排除分群不可以选择多个 CRM 标签", []);
            }
        }
        */

        $userGroupModel = new UserGroup();

        $count = $userGroupModel->getMergeGroupCount($siteName, $userDefineGroup, $sysGroup, $excludeGroup);
        $this->returnJson(0, "success", ["count" => $count]);
    }

    /**
     * 是否有重复的分群
     */
    public function actionIsDuplicate()
    {
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method("user_group_id");
        $siteId = yii::$app->request->$method("site_id");
        $groupName = yii::$app->request->$method("user_group_name");
        var_dump($groupName);

        if (empty($siteId) || empty($groupName)) {
            $this->returnJson(10001, "数据不完整");
        }

        $result = $this->isDuplicate($siteId, $groupName, $userGroupId);
        if (false === $result) {
            $this->returnJson(0, "success", ["is_duplicate" => 0]);
        } else {
            $this->returnJson(0, "success", ["is_duplicate" => 1]);
        }
    }

    /**
     * 是否有重复的分群
     * @param $siteId                   站点id
     * @param $userGroupName            分群名称
     * @param null $userGroupId 分群id
     * @return bool
     */
    private function isDuplicate($siteId, $userGroupName, $userGroupId = null)
    {
        $userGroupModel = new UserGroup();
        $group = $userGroupModel->getByCondition(["site_id" => $siteId, "user_group_name" => $userGroupName, "is_del" => 0]);
        if (empty($group)) {
            return false;
        }
        if (!empty($userGroupId) && $userGroupId == $group[0]["user_group_id"]) {
            return false;
        }
        return true;
    }


    /**
     * 管理后台定时拉取分群数据表的值
     */
    public function actionGetUserGroup()
    {
        $method = yii::$app->request->getMethod();
        $userGroupId = yii::$app->request->$method("user_group_id");
        $userGroupModel = new UserGroup();
        $userGroupData = $userGroupModel->getUserGroupById($userGroupId);
        $this->returnJson(0, "success", $userGroupData);
    }

    /**
     * ajax异步获取 站点用户标签队列
     *
     * /marketing/user-group/get-user-label-ajax?site=marketing_email
     */
    public function actionGetUserLabelAjax()
    {
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $formData['site_id'] = !empty($formData['site_id']) ? intval($formData['site_id']) : 0;
        $result = [];
        self::checkUpdateLabeState();
        try {

//            switch($formData['site_id']){
//                case "12":
//                    $site = 'gearbest';
//                    break;
//
//                case "19":
//                    $site = 'zaful';
//                    break;
//
//                default:
//                    throw new yii\base\Exception("暂只对接了 gearbest、zaful站");
//            }
            $site = Site::getInstance()->getSiteShortNameById($formData['site_id']);
            $userLabelList = (new UserLabelQueue())->getQueueListBySite($site);

            $queue_id = 0;
            if (!empty($formData['user_group_id'])) {
                $sql = "select user_label_con from user_group where user_group_id ={$formData['user_group_id']} ";
                $labelInfo = Yii::$app->db->createCommand($sql)->queryScalar();
                if (!empty($labelInfo)) {
                    $userLabel = \GuzzleHttp\json_decode($labelInfo, true);
                    if (!empty($userLabel['queue_id'])) {
                        $queue_id = $userLabel['queue_id'];
                    }
                }
            }

            $index = 0;
            if (!empty($userLabelList)) {
                foreach ($userLabelList as $key => $val) {

                    $result[$index] = [
                        'queue_id' => $val['queue_id'],
                        'queue_name' => $val['queue_name'],
                        'labels' => $val['labels'],
                        'type' => $val['type'],
                        'defualt' => "0",   //不默认展示
                        'short_labels' => mb_substr($val['labels'], 0, 32, 'utf-8') . ">>"
                    ];

                    if (!empty($queue_id) && $val['queue_id'] == $queue_id) {
                        $result[$index]['defualt'] = "1";
                    }
                    ++$index;
                }
            }

        } catch (yii\base\Exception $exp) {

        }

        echo json_encode($result);
        exit;
    }

    /**
     * @Explain : 用户分群添加用户标签，选中邮件事件列表
     * @Param [type => "group_name= 分组名称,template_name= 发送邮件名称(模板名称),template_type =邮件模板类型",site_id => '网站id",site=>"marketing_email"]
     * @Author xianxuefeng
     * @Date 2018/8/13
     *
     */
    public function actionMailLabelList()
    {
        $method = yii::$app->request->getMethod();
        yii::$app->request->$method("site");
        $formData = yii::$app->request->$method();
        $site_id = !empty($formData['site_id']) ? intval($formData['site_id']) : 0;
        $type = isset($formData['type']) ? $formData['type'] : null;
        $stamp = strtotime("-30 day");    //获取30天前的时间戳
        switch ($type) {
            case 'group_name' :        // 分组名称
//                $sql = "select group_id as id,group_name as even_name from mail_group where site_id = {$site_id} and state=2 and is_inside_test = 0 and group_last_send > {$stamp} GROUP BY group_id order by group_last_send desc ";
                $sql = "select group_id as id,group_name as even_name from mail_group where site_id = {$site_id} and state=2 and is_inside_test = 0 and
 ((group_last_send > {$stamp} and is_ab_test = 0  ) or (group_last_send > {$stamp} and  is_ab_test = 1 and ab_test_parent_id > 0 )) 
 GROUP BY group_id order by group_last_send desc ";
                break;
            case 'template_name' :        // 发送邮件名称(模板名称)
                /*              $sql = "select GROUP_CONCAT(DISTINCT template_id) from mail_group where site_id = {$site_id} and state=2 and is_inside_test = 0 and group_last_send > {$stamp}  order by group_last_send desc ";
                */
                $sql = "select GROUP_CONCAT(DISTINCT template_id) from mail_group where site_id = {$site_id} and state=2 and is_inside_test = 0 and
  ((group_last_send > {$stamp} and is_ab_test = 0  ) or (group_last_send > {$stamp} and  is_ab_test = 1 and ab_test_parent_id > 0 )) 
  order by group_last_send desc ";

                $template_id_str = Yii::$app->db->createCommand($sql)->queryScalar();

                if (empty($template_id_str)) {
                    exit(json_encode(['status' => 1, 'msg' => "没有更多信息", 'data' => []]));
                }

                $sql = "select DISTINCT template_id as id,template_name as even_name from mail_template where status=1 and template_id in 
($template_id_str)  GROUP BY template_id  ";
                break;
            case 'template_type' :        // 邮件模板类型
                /* $sql = "select GROUP_CONCAT(DISTINCT template_id) from mail_group where site_id = {$site_id} and state=2  and is_inside_test = 0 and group_last_send > {$stamp}  order by group_last_send desc";
                */
                $sql = "select GROUP_CONCAT(DISTINCT template_id) from mail_group where site_id = {$site_id} and state=2  and is_inside_test = 0 and 
   ((group_last_send > {$stamp} and is_ab_test = 0  ) or (group_last_send > {$stamp} and  is_ab_test = 1 and ab_test_parent_id > 0 )) 
  order by group_last_send desc";

                $template_id_str = Yii::$app->db->createCommand($sql)->queryScalar();
                if (empty($template_id_str)) {
                    exit(json_encode(['status' => 1, 'msg' => "没有更多信息", 'data' => []]));
                }

                $sql = "select  GROUP_CONCAT(DISTINCT type_id) from mail_template where status=1 and template_id in ({$template_id_str})  ";
                $mail_template_str = Yii::$app->db->createCommand($sql)->queryScalar();

                if (empty($template_id_str)) {
                    exit(json_encode(['status' => 1, 'msg' => "没有更多信息", 'data' => []]));
                }

                $sql = "select id ,template_type_name as even_name from template_type where state=1 and id in ({$mail_template_str}) GROUP BY id";

                /* $sql = "select id ,template_type_name as even_name from template_type where state=1 and id in
     (select  GROUP_CONCAT(DISTINCT type_id) from mail_template where status=1 and template_id in
     (select GROUP_CONCAT(DISTINCT template_id) from mail_group where site_id = {$site_id} and state=2 and real_send_time > {$stamp})) ";*/
                break;
            default:
                $msg = '类型有误';
                exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
                break;
        }
        $list = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($list)) {
            exit(json_encode(['status' => 1, 'msg' => "没有更多信息", 'data' => []]));
        }
        exit(json_encode(['status' => 1, 'msg' => '成功', 'data' => $list]));
    }

    /**
     * @Explain :添加标签
     * @params [
     *  "site"=>"marketing_email",
     *  "type" => "group_name= 分组名称,template_name= 发送邮件名称(模板名称),template_type =邮件模板类型",
     *  "even_name" => "邮件事件名称",
     *  "state" => "已发送=1，发送未打开=2，打开=3，打开未点击=4，点击=5，点击未下单=6，下单=7",
     *  "near_days" => "最近多少天",
     *  "site_id" => "网站id",
     *  "id"  => "mail-label-list 接口返回的id ",
     *  "label_name" => '标签名',
     *
     * ]
     * @Author xianxuefeng
     * @Date 2018/8/13
     *
     */
    public function actionAddMailLabelNew()
    {
        set_time_limit(0);
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $res = ['status' => 0, 'msg' => '失败', 'data' => []];
        if (!isset($formData['site_id']) || !is_numeric($formData['site_id'])) {
            $res['msg'] = "site_id 不能为空且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['type']) || empty($formData['type'])) {
            $res['msg'] = "type 不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['state']) || !is_numeric($formData['state'])) {
            $res['msg'] = "state 不能为空 且必须为数字 ";
            exit(json_encode($res));
        }
        if (!isset($formData['near_days']) || !is_numeric($formData['near_days'])) {
            $formData['near_days'] = 30;   //产品特别要求，要这里写死
        }
        if (!isset($formData['id']) || !is_numeric($formData['id'])) {
            $res['msg'] = "id 不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['even_name']) || empty($formData['even_name'])) {
            $res['msg'] = "邮件事件名不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['label_name']) || empty($formData['label_name'])) {
            $res['msg'] = "标签名不能为空 且必须为数字";
            exit(json_encode($res));
        }
        $session = Yii::$app->session;
        $reviserRealName = isset($session['admin_info']['real_name']) ? $session['admin_info']['real_name'] : "system";    //用户名
        $siteName = Site::getInstance()->getSiteShortNameById($formData['site_id']);
        $stamp = strtotime("-{$formData['near_days']} day");    //最近天的时间戳
        //判断标签名是否重复
        $label_name_exist = Yii::$app->db->createCommand("select queue_name from crm_user_label_queue where  site = '{$siteName}' and queue_name = '{$formData['label_name']}' ")->queryScalar();
        if (!empty($label_name_exist)) {    //标签名已经存在
            $res['msg'] = "标签名已经存在,请起别名";
            exit(json_encode($res));
        }
        switch ($formData['type']) {    //获取group_id
            case 'group_name' :        // 分组名称
                $sql = "select  group_id as group_id_str,group_name as group_name_str from mail_group where group_id = {$formData['id']}";
                break;
            case 'template_name' :        // 发送邮件名称(模板名称)
                $sql = "select GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str from
 mail_group where template_id = {$formData['id']} and site_id = {$formData['site_id']} and state=2 and group_last_send > {$stamp} ";
                break;
            case 'template_type' :        // 邮件模板类型
                $sql = "select GROUP_CONCAT(DISTINCT template_id) from 
mail_template where type_id = {$formData['id']} and site_id ={$formData['site_id']} and status=1 ";

                $template_id_str = Yii::$app->db->createCommand($sql)->queryScalar();
                if (empty($template_id_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '没有筛选出用户信息', 'data' => []]));
                }
                $sql = "SELECT GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str 
FROM mail_group WHERE template_id IN ({$template_id_str}) AND state = 2
AND group_last_send > {$stamp}";
                break;
            default:
                $msg = '类型有误';
                exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
                break;
        }
        $list = Yii::$app->db->createCommand($sql)->queryOne();
        $group_id_str = isset($list['group_id_str']) ? $list['group_id_str'] : "";
        if (empty($group_id_str)) {
            exit(json_encode(['status' => 0, 'msg' => '没有筛选出用户信息', 'data' => []]));
        }
        $list['site_id'] = $formData['site_id'];
        $stateName = ['1' => '已发送', '2' => '发送未打开', '3' => '打开', '4' => '打开未点击', '5' => '点击', '6' => '点击未下单', '7' => '下单'];
        // 邮件状态筛选(已发送=1，发送未打开=2，打开=3，打开未点击=4，点击=5，点击未下单=6，下单=7)

        $sendListModel = new MailSendlist();

        $sendlistTable = $sendListModel->getSendListTable($formData['site_id'],$group_id_str,"site_user_id,email");

        if (empty($sendlistTable)) {
            exit(json_encode(['status' => 0, 'msg' => '没有筛选出用户信息', 'data' => []]));
        }
       // $sendlistTable = 'mail_sendlist_' . $siteName;
        $openTable = "email_{$siteName}_open_data";
        switch ($formData['state']) {
            case '1' :
                //DISTINCT site_user_id  as user_id  标记详情存储的是网站user_id
//                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where group_id in($group_id_str) and state = 2 and site_user_id !=0 ";
//                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where group_id in($group_id_str) and state = 2 and site_user_id !=0 ";
                $sql = "select site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 ";
                $sqlcount = "select count(site_user_id) from {$sendlistTable} where  site_user_id !=0 ";
                break;
            case '2' :  //open_count = 0 没有打开
                //是否存在打开数量
                $existOpenNum = self::existOpenTotal($openTable,$group_id_str);
                if (empty($existOpenNum)) {
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0  ";
                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 ";
                }else {
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 and site_user_id not in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) ";
                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 and site_user_id not in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) ";
                }

                break;
            case '3' :  //open_count = 0 打开
//                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where group_id in($group_id_str) and state = 2 and open_count >0 and site_user_id !=0  ";
//                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where group_id in($group_id_str) and state = 2 and open_count >0 and site_user_id !=0 ";

                $sql = "select DISTINCT site_user_id  as user_id  from $openTable where group_id in ($group_id_str) ";
                $sqlcount = "select count(DISTINCT site_user_id) from $openTable where group_id in ($group_id_str)  ";


                break;
            case '4' :  //open_count > 0 打开 is_click_link = 0 未点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {

                    $sql = "select DISTINCT site_user_id  as user_id  from $openTable where group_id in ($group_id_str) ";
                    $sqlcount = "select count(DISTINCT site_user_id) from $openTable where group_id in ($group_id_str)  ";

                } else {
                    //打开数据库没有存邮箱，所以取sendlist表
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 and site_user_id  in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) and email not in ({$chick_str}) ";

                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 and site_user_id  in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) and email not in ({$chick_str})";

                    /*
                    $sql = "select distinct site_user_id  as user_id  from {$sendlistTable} where group_id in($group_id_str) and open_count >0  and email not in ({$chick_str}) and site_user_id !=0  ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where group_id in($group_id_str) and open_count >0  and email not in ({$chick_str}) and site_user_id !=0 ";
                    */
                }


                break;
            case '5' :  //is_click_link = 1 点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '此条件的用户数为零', 'data' => []]));
                }

                /*
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where group_id in($group_id_str) and email in ({$chick_str}) and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where group_id in($group_id_str) and  email in ({$chick_str}) and site_user_id !=0 ";
                */
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where email in ({$chick_str}) and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where email in ({$chick_str}) and site_user_id !=0 ";
                break;
            case '6' :  // 点击未下单
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '此条件的用户数为零', 'data' => []]));
                }
               
                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  email in ({$chick_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where  email in ({$chick_str})  and site_user_id !=0 ";
                } else {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  email in ({$chick_str}) and site_user_id not in ({$site_user_id_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where email in ({$chick_str}) and site_user_id not in ({$site_user_id_str}) and site_user_id !=0  ";
                }
                break;
            case '7' :  // 下单
                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '此条件的用户数为零', 'data' => []]));
                }
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  site_user_id in ({$site_user_id_str})  and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where site_user_id in ({$site_user_id_str}) and site_user_id !=0  ";
                break;
            default :
                $msg = '类型有误';
                exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
                break;
        }
        // 没有符合条件的筛选，直接返回
        $count = Yii::$app->db->createCommand($sqlcount)->queryScalar();
        if (empty($count)) {
            $msg = '此条件的用户数为零';
            exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
        }
        if (empty($formData['near_days'])) {
            $data['labels'] = $formData['even_name'] . "  <font color='blue'>and</font> " . $stateName[$formData['state']];    //组合条件
        } else {
            $data['labels'] = $formData['even_name'] . "  <font color='blue'>and</font> " . "近{$formData['near_days']}天" . " <font color='blue'>and</font> " . $stateName[$formData['state']];    //组合条件
        }


        $data['sql'] = $sql;
        $data['count'] = $count;
        $data['site_id'] = $formData['site_id'];
        $data['site_name'] = $siteName;
        $data['label_name'] = $formData['label_name'];
        $data['create_user'] = $data['update_user'] = $reviserRealName;

        if ($count < 10000) {
            $response = self::insertUserLable($data);
            if (empty($response)) {
                exit(json_encode(['status' => 0, 'msg' => '失败', 'data' => []]));
            }
            // 插入crm_user_label_queue 表数据
            exit(json_encode(['status' => 1, 'msg' => '成功', 'data' => []]));
        }

        
        $queue_id = self::getQueryId();
        $pushData = [
            'batch_id' => 0,
            'queue_id' => $queue_id,
            'queue_name' => $data['label_name'],    //标签名
            'labels' => $data['labels'],
            'count' => $data['count'],
            'site' => $data['site_name'],
            'create_user' => $data['create_user'],
            'type' => 1,  //用户添加
        ];
        $queueInfo = self::addQueue($pushData);
        if (empty($queueInfo)) {
            exit(json_encode(['status' => 0, 'msg' => '失败', 'data' => []]));
        }
        $data['queue_info'] = $queueInfo;
        $data['push_data'] = $pushData;
//        $domain_name = Yii::$app->params['binding_server'];
//        $data['web_url'] = $domain_name .'/crontab/crm-push/insert-user-lable?module_name=marketing_email';
        $data['web_url'] = '/crontab/crm-push/insert-user-lable?module_name=marketing_email';
        $redis = new RedisMarketingEmail();
        $key = "inser_user_lable_".uniqid();
        $data['key'] = "asynchronous_processing";
        $data['field'] = $key;
        $response = $redis->hset('asynchronous_processing',$data['field'],\GuzzleHttp\json_encode($data));

        if (empty($response)) {
            exit(json_encode(['status' => 0, 'msg' => '失败', 'data' => []]));
        }
        // 插入crm_user_label_queue 表数据
        exit(json_encode(['status' => 1, 'msg' => '成功', 'data' => []]));
    }



    /**
     * @Explain :添加标签
     * @params [
     *  "site"=>"marketing_email",
     *  "type" => "group_name= 分组名称,template_name= 发送邮件名称(模板名称),template_type =邮件模板类型",
     *  "even_name" => "邮件事件名称",
     *  "state" => "已发送=1，发送未打开=2，打开=3，打开未点击=4，点击=5，点击未下单=6，下单=7",
     *  "near_days" => "最近多少天",
     *  "site_id" => "网站id",
     *  "id"  => "mail-label-list 接口返回的id ",
     *  "label_name" => '标签名',
     *
     * ]
     * @Author xianxuefeng
     * @Date 2018/8/13
     *
     */
    public function actionAddMailLabel()
    {
        set_time_limit(0);
        $method = yii::$app->request->getMethod();
        $formData = yii::$app->request->$method();
        $res = ['status' => 0, 'msg' => '失败', 'data' => []];
        if (!isset($formData['site_id']) || !is_numeric($formData['site_id'])) {
            $res['msg'] = "site_id 不能为空且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['type']) || empty($formData['type'])) {
            $res['msg'] = "type 不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['state']) || !is_numeric($formData['state'])) {
            $res['msg'] = "state 不能为空 且必须为数字 ";
            exit(json_encode($res));
        }
        if (!isset($formData['near_days']) || !is_numeric($formData['near_days'])) {
            $formData['near_days'] = 30;   //产品特别要求，要这里写死
        }
        if (!isset($formData['id']) || !is_numeric($formData['id'])) {
            $res['msg'] = "id 不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['even_name']) || empty($formData['even_name'])) {
            $res['msg'] = "邮件事件名不能为空 且必须为数字";
            exit(json_encode($res));
        }
        if (!isset($formData['label_name']) || empty($formData['label_name'])) {
            $res['msg'] = "标签名不能为空 且必须为数字";
            exit(json_encode($res));
        }
        $session = Yii::$app->session;
        $reviserRealName = isset($session['admin_info']['real_name']) ? $session['admin_info']['real_name'] : "system";    //用户名
        $siteName = Site::getInstance()->getSiteShortNameById($formData['site_id']);
        $stamp = strtotime("-{$formData['near_days']} day");    //最近天的时间戳
        //判断标签名是否重复
        $label_name_exist = Yii::$app->db->createCommand("select queue_name from crm_user_label_queue where  site = '{$siteName}' and queue_name = '{$formData['label_name']}' ")->queryScalar();
        if (!empty($label_name_exist)) {    //标签名已经存在
            $res['msg'] = "标签名已经存在,请起别名";
            exit(json_encode($res));
        }
        switch ($formData['type']) {    //获取group_id
            case 'group_name' :        // 分组名称
                $sql = "select  group_id as group_id_str,group_name as group_name_str from mail_group where group_id = {$formData['id']}";
                break;
            case 'template_name' :        // 发送邮件名称(模板名称)
                $sql = "select GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str from
 mail_group where template_id = {$formData['id']} and site_id = {$formData['site_id']} and state=2 and group_last_send > {$stamp} ";
                break;
            case 'template_type' :        // 邮件模板类型
                $sql = "select GROUP_CONCAT(DISTINCT template_id) from 
mail_template where type_id = {$formData['id']} and site_id ={$formData['site_id']} and status=1 ";

                $template_id_str = Yii::$app->db->createCommand($sql)->queryScalar();
                if (empty($template_id_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '没有筛选出用户信息', 'data' => []]));
                }
                $sql = "SELECT GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str 
FROM mail_group WHERE template_id IN ({$template_id_str}) AND state = 2
AND group_last_send > {$stamp}";
                break;
            default:
                $msg = '类型有误';
                exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
                break;
        }
        $list = Yii::$app->db->createCommand($sql)->queryOne();
        $group_id_str = isset($list['group_id_str']) ? $list['group_id_str'] : "";
        if (empty($group_id_str)) {
            exit(json_encode(['status' => 0, 'msg' => "没有筛选出用户信息", 'data' => []]));
        }
        // 邮件状态筛选(已发送=1，发送未打开=2，打开=3，打开未点击=4，点击=5，点击未下单=6，下单=7)
        $stateName = ['1' => '已发送', '2' => '发送未打开', '3' => '打开', '4' => '打开未点击', '5' => '点击', '6' => '点击未下单', '7' => '下单'];
        // $group_id 拆分
        $group_id_arr = explode(",",$group_id_str);
        $new_group_id_str = "";
        $old_group_id_str = "";
        $SplitSendlist = new SplitSendlist();
        foreach ($group_id_arr as $val ) {
            if ($val > $SplitSendlist->splitGroupIdLimit) {
                $new_group_id_str .= "{$val},";
                continue;
            }
            $old_group_id_str .= "{$val},";
        }
        $newCount = 0;
        $oldCount = 0;
        $sqlArr = [];
        if (! empty($new_group_id_str)) {
            $new_group_id_str = trim($new_group_id_str,",");
            $newSendRes = self::newSendlistSel($new_group_id_str,$siteName,$formData);
            if (isset($newSendRes['sqlcount'],$newSendRes['sql']) && ! empty($newSendRes['sqlcount']) && ! empty($newSendRes['sql'])) {
                $newCount = Yii::$app->db->createCommand($newSendRes['sqlcount'])->queryScalar();
                if (! empty($newCount)) {
                    $sqlArr[] = $newSendRes['sql'];
                }
            }
        }

        if (! empty($old_group_id_str)) {
            $old_group_id_str = trim($old_group_id_str,",");
            $oldSendRes = self::oldSendlistSel($old_group_id_str,$siteName,$formData);
            if (isset($oldSendRes['sqlcount'],$oldSendRes['sql']) && ! empty($oldSendRes['sqlcount']) && ! empty($oldSendRes['sql'])) {
                $oldCount = Yii::$app->db->createCommand($oldSendRes['sqlcount'])->queryScalar();
                if (! empty($oldCount)) {
                    $sqlArr[] = $oldSendRes['sql'];
                }
            }
        }

        // 没有符合条件的筛选，直接返回
        $count = $newCount + $oldCount;
        if (empty($count)) {
            $msg = '此条件的用户数为零';
            exit(json_encode(['status' => 0, 'msg' => $msg, 'data' => []]));
        }
        if (empty($formData['near_days'])) {
            $data['labels'] = $formData['even_name'] . "  <font color='blue'>and</font> " . $stateName[$formData['state']];    //组合条件
        } else {
            $data['labels'] = $formData['even_name'] . "  <font color='blue'>and</font> " . "近{$formData['near_days']}天" . " <font color='blue'>and</font> " . $stateName[$formData['state']];    //组合条件
        }

        $data['sql'] = $sql;
        $data['count'] = $count;
        $data['site_id'] = $formData['site_id'];
        $data['site_name'] = $siteName;
        $data['label_name'] = $formData['label_name'];
        $data['create_user'] = $data['update_user'] = $reviserRealName;

        $queue_id = self::getQueryId();
        $pushData = [
            'batch_id' => 0,
            'queue_id' => $queue_id,
            'queue_name' => $data['label_name'],    //标签名
            'labels' => $data['labels'],
            'count' => $count,
            'site' => $siteName,
            'create_user' => $reviserRealName,
            'type' => 1,  //用户添加
        ];
        $queueInfo = self::addQueue($pushData);
        if (empty($queueInfo)) {
            exit(json_encode(['status' => 0, 'msg' => '失败', 'data' => []]));
        }
        unset($sql,$data);
        foreach ($sqlArr as $key => & $sql) {
            $pageStart = 0;
            $offset = 0;
            $size = 1000; // 每次执行的大小
            if ( $key==0 && count($sqlArr) > 1) {   //第一条sql去重
               $sql .= " and site_user_id not in($sqlArr[1])";
            }
            while (true) {
                $tmpSql = $sql . " limit {$size} OFFSET {$offset} ";
                $userList = Yii::$app->db->createCommand($tmpSql)->queryAll();
                if (empty($userList) || !is_array($userList)) {
                    break;
                }
                $userArr = [];
                foreach ($userList as $val) {
                    $userArr[] = $val['user_id'];
                }
                $pushData['user_ids'] = $userArr;
                //保存详情数据
                self::addQueueDetail($queueInfo['queue_detail_name'], $pushData);
                ++$pageStart;
                $offset = $pageStart * $size;
            }
        }
        $status = 2;
        if ($siteName == 'gearbest' || $siteName == 'zaful') {   // 目前gearbest 和 zaful 数据导入要同步到es才算完成
            $status = 1;
        }

        // 更新标签添加状态
        $updateData = [
            'status' => $status,
            'update_user' => $reviserRealName,
            'update_time' => yii::$app->systime->time(),
        ];
        $updateWhere = [
            'queue_id' => $queueInfo['queue_id']
        ];
        $affectedRows = Yii::$app->db->createCommand()->update('crm_user_label_queue', $updateData, $updateWhere)->execute();
        exit(json_encode(['status' => 1, 'msg' => '成功', 'data' => []]));
    }

    /**
     *  新的sendlist 筛选sql
     *  return sql
     */
    private function newSendlistSel($group_id_str,$siteName,$formData) {
        $res = ['sql'=>'','sqlcount'=>''];
        $sql = "select GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str from mail_group where group_id in($group_id_str)";
        $list = Yii::$app->db->createCommand($sql)->queryOne();
        if (empty($list)) {
            return $res;
        }
        $list['site_id'] = $formData['site_id'];
        $sendListModel = new MailSendlist();
        $sendlistTable = $sendListModel->getSendListTable($formData['site_id'],$group_id_str,"site_user_id,email");

        if (empty($sendlistTable)) {
            return $res;
        }
        // $sendlistTable = 'mail_sendlist_' . $siteName;
        $openTable = "email_{$siteName}_open_data";
        switch ($formData['state']) {
            case '1' :
                $sql = "select site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 ";
                $sqlcount = "select count(site_user_id) from {$sendlistTable} where  site_user_id !=0 ";
                break;
            case '2' :  //open_count = 0 没有打开
                //是否存在打开数量
                $existOpenNum = self::existOpenTotal($openTable,$group_id_str);
                if (empty($existOpenNum)) {
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0  ";
                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 ";
                }else {
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 and site_user_id not in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) ";
                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 and site_user_id not in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) ";
                }

                break;
            case '3' :  //open_count = 0 打开

                $sql = "select DISTINCT site_user_id  as user_id  from $openTable where group_id in ($group_id_str) ";
                $sqlcount = "select count(DISTINCT site_user_id) from $openTable where group_id in ($group_id_str)  ";
                break;
            case '4' :  //open_count > 0 打开 is_click_link = 0 未点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    $sql = "select DISTINCT site_user_id  as user_id  from $openTable where group_id in ($group_id_str) ";
                    $sqlcount = "select count(DISTINCT site_user_id) from $openTable where group_id in ($group_id_str)  ";

                } else {
                    //打开数据库没有存邮箱，所以取sendlist表
                    $sql = "select  site_user_id  as user_id  from {$sendlistTable} where site_user_id !=0 and site_user_id  in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) and email not in ({$chick_str}) ";

                    $sqlcount = "select count( site_user_id) from {$sendlistTable} where site_user_id !=0 and site_user_id  in(select DISTINCT site_user_id from $openTable where group_id in ($group_id_str)) and email not in ({$chick_str})";

                }
                break;
            case '5' :  //is_click_link = 1 点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    return $res;
                }
 $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where email in ({$chick_str}) and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where email in ({$chick_str}) and site_user_id !=0 ";
                break;
            case '6' :  // 点击未下单
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    return $res;
                }
                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  email in ({$chick_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where  email in ({$chick_str})  and site_user_id !=0 ";
                } else {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  email in ({$chick_str}) and site_user_id not in ({$site_user_id_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where email in ({$chick_str}) and site_user_id not in ({$site_user_id_str}) and site_user_id !=0  ";
                }
                break;
            case '7' :  // 下单
                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    return $res;
                }
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTable} where  site_user_id in ({$site_user_id_str})  and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTable} where site_user_id in ({$site_user_id_str}) and site_user_id !=0  ";
                break;
            default :
                return $res;
        }
        return ['sql' =>$sql,'sqlcount'=>$sqlcount];
    }

    /**
     *  旧的sendlist 筛选sql
     *
     *  return sql
     */
    private function oldSendlistSel($group_id_str,$siteName,$formData) {
        $res = ['sql'=>'','sqlcount'=>''];
        $sql = "select GROUP_CONCAT(DISTINCT group_id) AS group_id_str,GROUP_CONCAT(DISTINCT group_name) AS group_name_str from mail_group where group_id in ($group_id_str)";
        $list = Yii::$app->db->createCommand($sql)->queryOne();
        if (empty($list)) {
            return $res;
        }
        $list['site_id'] = $formData['site_id'];
        $sendlistTeble = 'mail_sendlist_' . $siteName;

        switch ($formData['state']) {
            case '1' :
                //DISTINCT site_user_id  as user_id  标记详情存储的是网站user_id
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and site_user_id !=0 ";
                break;
            case '2' :  //open_count = 0 没有打开
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and open_count = 0 and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and open_count = 0 and site_user_id !=0 ";
                break;
            case '3' :  //open_count = 0 打开
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and open_count >0 and site_user_id !=0  ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and open_count >0 and site_user_id !=0 ";
                break;
            case '4' :  //open_count > 0 打开 is_click_link = 0 未点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    $sql = "select distinct site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and open_count >0  and site_user_id !=0  ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and open_count >0   and site_user_id !=0 ";
                } else {
                    $sql = "select distinct site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and open_count >0  and email not in ({$chick_str}) and site_user_id !=0  ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and open_count >0  and email not in ({$chick_str}) and site_user_id !=0 ";
                }
                break;
            case '5' :  //is_click_link = 1 点击
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                    return $res;
                }
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and email in ({$chick_str}) and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and  email in ({$chick_str}) and site_user_id !=0 ";
                break;
            case '6' :  // 点击未下单
                $chick_str = self::getChickEmail($group_id_str);
                if (empty($chick_str)) {
                   return $res;
                }

                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str)  and email in ({$chick_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and email in ({$chick_str})  and site_user_id !=0 ";
                } else {
                    $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str)and email in ({$chick_str}) and site_user_id not in ({$site_user_id_str})  and site_user_id !=0 ";
                    $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str)  and email in ({$chick_str}) and site_user_id not in ({$site_user_id_str}) and site_user_id !=0  ";
                }
                break;
            case '7' :  // 下单
                //获取下单的用户site_user_id
                $site_user_id_str = self::getOrderSiteUserId($list);
                if (empty($site_user_id_str)) {
                    exit(json_encode(['status' => 0, 'msg' => '此条件的用户数为零', 'data' => []]));
                }
                $sql = "select DISTINCT site_user_id  as user_id  from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and site_user_id in ({$site_user_id_str})  and site_user_id !=0 ";
                $sqlcount = "select count(DISTINCT site_user_id) from {$sendlistTeble} where group_id in($group_id_str) and state = 2 and site_user_id in ({$site_user_id_str}) and site_user_id !=0  ";
                break;
            default :
                return $res;
        }
        $res['sql'] = $sql;
        $res['sqlcount'] = $sqlcount;
        return $res;
    }

    /**
     * 获取分组的打开数量
     * @param string $openTable ,string $group_id_str
     * @author  xianxuefeng
     * @date 2018/8/31
     * @return bool
     */
     private function existOpenTotal($openTable,$group_id_str) {
         if (empty($openTable) || empty($group_id_str)) {
             return false;
         }
         $sql = "select count(site_user_id) from $openTable where group_id in ($group_id_str)";
         $openNum =    $count = Yii::$app->db->createCommand($sql)->queryScalar();
         if (empty($openNum)) {
             return false;
         }
         return true;
     }
    /**
     * @Explain : 获取网站的订单
     * @data['group_id_str' =>'','group_name_str' => '','site_id'=>'']
     * @author xianxuefeng
     * @date 2018/8/11
     * @return string
     */
    public function getOrderSiteUserId($data)
    {
        if (empty($data['group_id_str']) || empty($data['group_name_str']) || empty($data['site_id'])) {
            return '';
        }
        if ($data['site_id'] == 12) {
            $site_user_id_arr = [];
            $track_code_arr = explode(",", $data['group_name_str']);
            foreach ($track_code_arr as $track_code) {
                $sql = "select user_id from
gearbest_order_market_data where utm_campaign like '{$track_code}%' ";
                $orderInfo = yii::$app->db->createCommand($sql)->queryAll();
                foreach ($orderInfo as $site_user_id) {
                    $site_user_id_arr[] = $site_user_id['user_id'];
                }
            }
            if (empty($site_user_id_arr)) {
                return '';
            }
            $site_user_id_arr = array_unique($site_user_id_arr);
            return implode(",", $site_user_id_arr);
        }
        $sql = "select DISTINCT order_sn from 
vw_order_mail_info where group_id in({$data['group_id_str']})";
        $orderList = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($orderList)) {
            return '';
        }
        $order_sn_str = self::arr2str($orderList, 'order_sn', 'string');

        // no gearbest 订单
        /*
        $sql = "select GROUP_CONCAT( DISTINCT user_id ) as site_user_id from tb_eload_order_info where order_sn in (select GROUP_CONCAT( DISTINCT order_sn) as order_sn_str from
vw_order_mail_info where group_id in({$data['group_id_str']}))";*/
        $sql = "select GROUP_CONCAT( DISTINCT user_id ) as site_user_id from tb_eload_order_info where order_sn in ({$order_sn_str})";

        $userList = Yii::$app->db->createCommand($sql)->queryOne();
        if (empty($userList['site_user_id'])) {
            return '';
        }
        return $userList['site_user_id'];
    }


    /**
     * @Explain : 获取网站的订单
     * @data['group_id_str' =>'','group_name_str' => '','site_id'=>'']
     * @author xianxuefeng
     * @date 2018/8/11
     * @return string
     */
    public function getChickEmail($group_id_str)
    {
        if (empty($group_id_str) || empty($group_id_str)) {
            return '';
        }
        $sql = "select DISTINCT email from 
mail_trace_detail where gid in({$group_id_str}) and is_click = 1";
        $detailList = Yii::$app->db->createCommand($sql)->queryAll();
        if (empty($detailList)) {
            return '';
        }
        $email_str = self::arr2str($detailList, 'email', 'string');
        return $email_str;
    }

    /*
     *  @Explain : 获取网站的订单
     *  @Data ['sql' => '符合条件的sql语句','sqlcount' => '查看总数语句','site_name' => '网站名称','site_id' => '网站id']
     *  @Author xianxuefeng
     *  @Date 2018/8/14
     *  @Return bool
     */
    private function insertUserLable($data)
    {
        if (empty($data['count']) || empty($data['sql']) || empty($data['site_name'])) {
            return false;
        }
        //['batch_id','queue_id','queue_name','labels','count','site' => 'site_name']
        //保存基础信息，如果是第一次保存，需要创建详情信息表
        $queue_id = self::getQueryId();
        $pushData = [
            'batch_id' => 0,
            'queue_id' => $queue_id,
            'queue_name' => $data['label_name'],    //标签名
            'labels' => $data['labels'],
            'count' => $data['count'],
            'site' => $data['site_name'],
            'create_user' => $data['create_user'],
            'type' => 1,  //用户添加
        ];
        $queueInfo = self::addQueue($pushData);
        if (empty($queueInfo)) {
            return false;
        }
        $siteName = $pushData['site'];
//        $siteInfo = yii::$app->params['sites']['marketing_email']['web_config'][$siteName];
        $pageStart = 0;
        $offset = 0;
        $size = 1000; // 每次执行的大小
        while (true) {
            $tmpSql = $data['sql'] . " limit {$size} OFFSET {$offset} ";
            $userList = yii::$app->db->createCommand($tmpSql)->queryAll();
            if (empty($userList) || !is_array($userList)) {
                break;
            }
            $userArr = [];
            foreach ($userList as $val) {
                $userArr[] = $val['user_id'];
            }
            $pushData['user_ids'] = $userArr;
//            if (!empty($siteInfo['accessEs'])) {
//                (new UserLabelQueueDetail())->addQueueDetail($queueInfo['queue_detail_name'], $pushData);
//            } else {
            //保存详情数据
            self::addQueueDetail($queueInfo['queue_detail_name'], $pushData);
//            }
            ++$pageStart;
            $offset = $pageStart * $size;
        }


        $status = 2;
        if ($siteName == 'gearbest' || $siteName == 'zaful') {   // 目前gearbest 和 zaful 数据导入要同步到es才算完成
            $status = 1;
        }

        // 更新标签添加状态
        $updateData = [
            'status' => $status,
            'update_user' => $data['update_user'],
            'update_time' => yii::$app->systime->time(),
        ];
        $updateWhere = [
            'queue_id' => $queueInfo['queue_id']
        ];
        $affectedRows = Yii::$app->db->createCommand()->update('crm_user_label_queue', $updateData, $updateWhere)->execute();
        if (empty($affectedRows)) {
            return false;
        }
        return true;
    }

    /**
     *
     *
     *
     */
    private function addQueue($data)
    {

        $sql = " SELECT * FROM crm_user_label_queue WHERE 1=1 AND queue_id = :queue_id ";
        $params['queue_id'] = $data['queue_id'];
        $queueInfo = Yii::$app->db->createCommand($sql, $params)->queryOne();
        if (!empty($queueInfo)) {
            $queueInfo['queue_detail_name'] = 'crm_user_label_' . $data['site'];
            return $queueInfo;
        }
        return self::_create($data);
    }

    private function _create($data)
    {
        //判断表是否存在，不存在就创建
        $siteName = $data['site'];
        $tableName = 'crm_user_label_' . $siteName;
        $res = self::createTable($tableName);
        if (empty($res)) {
            Elog::logCrontab("in the _create function ,table is empty {$tableName} ", "userGroup_{$this->time}", "info");
            return [];
        }
        $type = isset($data['type']) ? $data['type'] : 0;
        $create_user = isset($data['create_user']) ? $data['create_user'] : "system";
        $update_user = isset($data['update_user']) ? $data['update_user'] : "system";
//        $status = 2;
//        if ($siteName == 'gearbest' || $siteName == 'zaful') {   // 目前gearbest 和 zaful 数据导入要同步到es才算完成
//            $status = 1;
//        }
        $insertData = [
            'batch_id' => $data['batch_id'],
            'queue_id' => $data['queue_id'],
            'queue_name' => $data['queue_name'],
            'labels' => $data['labels'],
            'count' => $data['count'],
            'site' => $data['site'],
//            'status' => $status, //推送中
            'status' => "1", //推送中
            'queue_detail_name' => $tableName,
            'create_user' => $create_user,
            'create_time' =>  yii::$app->systime->time(),   //北京时间
            'update_user' => $update_user,
            'update_time' =>  yii::$app->systime->time(),
            'type' => $type
        ];

        $res = Yii::$app->db->createCommand()->insert('crm_user_label_queue', $insertData)->execute();
        //$lastInsertId = Yii::$app->db->getLastInsertID();

        if (empty($res)) {
            Elog::logCrontab("in the _create function ,add crm_user_label_queue info failed  " . \GuzzleHttp\json_encode($insertData), "userGroup_{$this->time}", "info");
            return [];
        }
        //创建队列详情表
        return $insertData;
    }

    /**
     * yumao
     * 2018-5-30
     * @param type $queueInfo
     */
    private function getSiteCrmDetailTableName($queueInfo)
    {
        $detailTableName = 'crm_user_label';
        $detailTableName .= '_' . $queueInfo['site'];
        return $detailTableName;
    }

    /**
     * 创建队列详情数据
     *
     * @param $tableName
     * @param $pushData
     * @throws \yii\db\Exception
     */
    private function addQueueDetail($tableName, $pushData)
    {
        if (empty($pushData['user_ids'])) {
            return;
        }
        if (!is_array($pushData['user_ids'])) {
            return;
        }
        $columns = [
            'queue_id',
            'batch_id',
            'site_user_id',
            'appsflyer_id',
            'create_time'
        ];
        $rows = [];
        foreach ($pushData['user_ids'] as $key => $val) {
            $detailArray = explode("|", $val);
            $detailArray[0] = intval(isset($detailArray[0]) ? $detailArray[0] : 0);
            $detailArray[1] = intval(isset($detailArray[1]) ? $detailArray[1] : 0);
            $rows[] = [
                $pushData['queue_id'],
                $pushData['batch_id'],
                $detailArray[0],
                $detailArray[1],
                yii::$app->systime->time(),
            ];
        }
        Yii::$app->db->createCommand()->batchInsert($tableName, $columns, $rows)->execute();
    }
     
    /**
     * 创建一个新的队列详情表
     *
     * @param $tableName
     * @return bool
     * @throws \yii\db\Exception
     */
    public function createTable($tableName)
    {
        if (empty($tableName)) {
            return false;
        }
        $exist = self::_exitsTable($tableName);
        if (!empty($exist)) {
            return true;
        }

        $tableSql = "
            CREATE TABLE `{$tableName}` (
              `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
              `queue_id` INT(11) NOT NULL DEFAULT 0 COMMENT 'crm系统队列id',
              `batch_id` INT(11) NOT NULL DEFAULT 0 COMMENT 'crm系统队列id',
              `site_user_id` BIGINT(19) NOT NULL DEFAULT 0 COMMENT '网站用户id',
              `appsflyer_id` INT(11) NOT NULL DEFAULT 0 COMMENT '设备id',
              `create_time` INT(11) NOT NULL DEFAULT 0 COMMENT '修改时间',
              PRIMARY KEY (`id`),
              KEY `idx_user` (`site_user_id`),
              KEY `idx_queue` (`queue_id`)
            ) ENGINE=INNODB  DEFAULT CHARSET=utf8 COMMENT='用户标签详情'
        ";
        Yii::$app->db->createCommand($tableSql)->execute();

        return true;
    }

    /**
     * 判断表是否存在
     *
     * @param $tableName
     * @return array|false
     */
    protected function _exitsTable($tableName)
    {
        $tableExitsSql = " SELECT table_name FROM information_schema.TABLES WHERE table_name = :table_name";
        $tableExitsParams['table_name'] = $tableName;

        return Yii::$app->db->createCommand($tableExitsSql, $tableExitsParams)->queryOne();
    }


    /**
     * @Explain : 获取query_id 。手动导入query_id 设置成大于100万的id下标
     * @Author xianxuefeng
     * @Date 2018/8/14
     * @Return int | null
     */
    protected function getQueryId()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步

        $sql = "select queue_id from crm_user_label_queue order by queue_id desc limit 1";
        $crmUserLabelList = Yii::$app->db->createCommand($sql)->queryOne();
        if (empty($crmUserLabelList)) {
            return null;
        }
        if ($crmUserLabelList['queue_id'] < 1000000) {
            $crmUserLabelList['queue_id'] = 1000000;  //没有一百万，赋值一百万
        }
        return $crmUserLabelList['queue_id'] + 1;
    }

    /**
     * @Explain : 查看用户标签
     * @params ['site' => '','site_id'=>'网站id',"type" => "user_label 为用户标签 or all_label 全部标签包括crm"]
     * @Author : xianxuefeng
     * @Date 2018/8/14
     * @response {
     * "status":1,
     * "msg":"成功",
     * "data":[
     * {
     * "even_name":"yonghu",
     * "labels":"yonghu and 近1000天 and 已发送",
     * "status":"1",
     * "create_user":"system",
     * "create_time":"2018-14-08 02:50:47",
     * "type":"1"
     * }
     * ]
     * }
     *
     */

    public function actionGetLabelList()
    {
        set_time_limit(0);
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $method = yii::$app->request->getMethod();
        yii::$app->request->$method("site");
        $formData = $_REQUEST;
        if (!isset($formData['site_id']) || empty($formData['site_id'])) {
//            $this->sysMsg('警告', '网站ID不存在!',
//                [ 'type' => 'error', 'links' => [ ['name'=>'返回上一页' , 'url'=>'javascript:history.go(-1)'] ] ]);
            exit(json_encode(['status' => 0, 'msg' => '没有更多数据', 'data' => []]));
        }
        $siteName = Site::getInstance()->getSiteShortNameById($formData['site_id']);
        $nearlySevenDay = strtotime("-7 day");    //最近天的时间戳
        $where = " where del = 0 and site = '{$siteName}'  ";
        if (!isset($formData['type']) || $formData['type'] == "user_label") {   //七天内添加的用户标签
            $where = $where . " and type = 1 and create_time > $nearlySevenDay ";
        }
        /*

         $sql = "select id,queue_id,queue_name as even_name,labels,status,create_user,FROM_UNIXTIME(create_time,
'%Y-%m-%d %h:%i:%s')AS create_time,type,site,count,queue_detail_name from crm_user_label_queue {$where} order by id desc";
        */
        $sql = "select id,queue_id,queue_name as even_name,labels,status,create_user,create_time,type,site,count,queue_detail_name from crm_user_label_queue {$where} order by id desc";
        // echo $sql;
        $labelList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($labelList)) {
            exit(json_encode(['status' => 1, 'msg' => '没有更多数据', 'data' => []]));
        }

        foreach ($labelList as & $val) {
            $val['create_time'] = yii::$app->bjTime->date("Y-m-d h:i:s",$val['create_time']);
            if ($val['status'] == '2') {
                $val['status_name'] = '已完成';
                continue;
            }
            if ($val['site'] == 'gearbest' || $val['site'] == 'zaful') {   //zaful 和 gearbest 要查看是否同步到es成功
                $filters['filters'] = [['field' => 'queueIds', 'values' => [$val['queue_id']]]];
                $count = Yii::$app->es->setSite($siteName)->count($filters);
                if (empty($count)) {
                    $val['status_name'] = '0%';
                    continue;
                }
                $val['status_name'] = round(($count / $val['count']) * 100, 2) . "%";
                if (($count / $val['count']) >= 0.9) {   //更新此记录的数据同步状态
                    Yii::$app->db->createCommand()->update('crm_user_label_queue',
                        ['status' => 2, 'update_time' => Yii::$app->systime->time()], ['id' => $val['id']])->execute();
                    $val['status_name'] = '已完成';
                }
                continue;
            }
            $sql = "select count(*) from {$val['queue_detail_name']} where queue_id = {$val['queue_id']}";
            $count = yii::$app->db->createCommand($sql)->queryScalar();
            if (empty($count)) {
                $val['status_name'] = '0%';
                continue;
            }
            $val['status_name'] = round(($count / $val['count']) * 100, 2) . "%";
            if (($count / $val['count']) >= 0.98) {   //更新此记录的数据同步状态
                Yii::$app->db->createCommand()->update('crm_user_label_queue',
                    ['status' => 2, 'update_time' => yii::$app->bjTime->time()], ['id' => $val['id']])->execute();
                $val['status_name'] = '已完成';
            }
        }
        exit(json_encode(['status' => 1, 'msg' => '成功', 'data' => $labelList]));
        /*
         *
        {
            "filters":[
                {
                    "field":"queueIds",
                    "values":[
                        "172"
                    ]
                }
            ]
          }
         */

    }


    /**
     * @Explain 检测更新标签状态
     * @author xianxuefeng
     * @date 2018/8/23
     * @return   bool
     */
    public function checkUpdateLabeState()
    {
        set_time_limit(0);
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。防止生成子分组时主从不同步
        $method = yii::$app->request->getMethod();
        yii::$app->request->$method("site");
        $formData = $_REQUEST;
        if (!isset($formData['site_id']) || empty($formData['site_id'])) {
           return false;
        }
        $siteName = Site::getInstance()->getSiteShortNameById($formData['site_id']);
        $nearlySevenDay = strtotime("-14 day");    //最近天的时间戳
        $where = " where del = 0 and  site = '{$siteName}' ";
        if (!isset($formData['type']) || $formData['type'] == "user_label") {   //七天内添加的用户标签
            $where = $where . " and type = 1 and create_time > $nearlySevenDay ";
        }
        $sql = "select id,queue_id,queue_name as even_name,labels,status,create_user,FROM_UNIXTIME(create_time, 
'%Y-%m-%d %h:%i:%s')AS create_time,type,site,count,queue_detail_name from crm_user_label_queue {$where} order by id desc";
        // echo $sql;
        $labelList = yii::$app->db->createCommand($sql)->queryAll();
        if (empty($labelList)) {
           return true;
        }

        foreach ($labelList as & $val) {
            if ($val['status'] == '2') {
                $val['status_name'] = '已完成';
                continue;
            }
            if ($val['site'] == 'gearbest' || $val['site'] == 'zaful') {   //zaful 和 gearbest 要查看是否同步到es成功
                $filters['filters'] = [['field' => 'queueIds', 'values' => [$val['queue_id']]]];
                $count = Yii::$app->es->setSite($siteName)->count($filters);
                if (empty($count)) {
                    $val['status_name'] = '0%';
                    continue;
                }
                $val['status_name'] = round(($count / $val['count']) * 100, 2) . "%";
                if (($count / $val['count']) >= 0.9) {   //更新此记录的数据同步状态
                    Yii::$app->db->createCommand()->update('crm_user_label_queue',
                        ['status' => 2, 'update_time' => Yii::$app->systime->time()], ['id' => $val['id']])->execute();
                    $val['status_name'] = '已完成';
                }
                continue;
            }
            $sql = "select count(*) from {$val['queue_detail_name']} where queue_id = {$val['queue_id']}";
            $count = yii::$app->db->createCommand($sql)->queryScalar();
            if (empty($count)) {
                $val['status_name'] = '0%';
                continue;
            }
            $val['status_name'] = round(($count / $val['count']) * 100, 2) . "%";
            if (($count / $val['count']) >= 0.98) {   //更新此记录的数据同步状态
                Yii::$app->db->createCommand()->update('crm_user_label_queue',
                    ['status' => 2, 'update_time' => yii::$app->bjTime->time()], ['id' => $val['id']])->execute();
                $val['status_name'] = '已完成';
            }
        }
        return true;
    }
    /**
     * 测试es
     */
    public function actionLabelCount()
    {

        set_time_limit(0);
        $method = yii::$app->request->getMethod();
        yii::$app->request->$method("site");
        $formData = $_REQUEST;
        if (empty($formData['site_id'])) {
            echo "site_id 不能为空";
        }
        if (empty($formData['queue_id'])) {
            echo "queue_id 不能为空";
        }
        $siteName = Site::getInstance()->getSiteShortNameById($formData['site_id']);
        $filters['filters'] = [['field' => 'queueIds', 'values' => [$formData['queue_id']]]];
        $count = Yii::$app->es->setSite($siteName)->count($filters);
        echo "<pre/>";
        print_r($count);
    }

    /**
     * 返回二维数组，指定下标，值非空的$delimiter分隔字符串,$delimiter 默认为逗号
     * 返回逗号分隔字符串
     *
     */
    private function arr2str($array, $key, $type = 'int', $delimiter = ',')
    {
        if (empty($array) || empty($key)) {
            return false;
        }
        $string = '';
        if ($type == 'int') {
            foreach ($array as $val) {
                if (isset($val[$key]) && !empty($val[$key])) {
                    $string .= $val[$key] . $delimiter;
                }
            }
        } else {
            foreach ($array as $val) {
                if (isset($val[$key]) && !empty($val[$key])) {
                    $string .= "'{$val[$key]}'$delimiter";
                }
            }
        }
        return rtrim($string, $delimiter);
    }

}
